当前位置:网站首页>如何求最大公约数?
如何求最大公约数?
2022-08-09 12:25:00 【进击的李知因】
1、在1~m/2之间找约数,最后的约数即最大公约数
public class Case25_GreatestCommonDivisor{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入两个正整数:");
int m = in.nextInt();
int n = in.nextInt();
int gcd = 1;
if(m>n) //交换,确保m为较小者
{
m = m^n;
n = m^n;
m = m^n;
}
if(m == n || n%m == 0)
{
System.out.printf("%d与%d的最大公约数是%d\n",m,n,m);
System.exit(0);
}
//找约数,最后的即最大公约数
for(int i = 1; i <= m/2; i++)
if(m%i==0 && n%i==0)
gcd = i;
System.out.printf("%d与%d的最大公约数是%d\n",m,n,gcd);
}
}
2、在m/2~1之间找约数,找到就退出循环
for(int i = m/2; i > 0; i--)
if(m%i==0 && n%i==0)
{
gcd = i;
break;
}
3、欧几里德算法(辗转相除法)
public class Case25_GreatestCommonDivisor{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入两个正整数:");
int m = in.nextInt();
int n = in.nextInt();
if(m>n) //交换,确保m为较小者
{
m = m^n;
n = m^n;
m = m^n;
}
while(n%m != 0)
{
int temp = m;
m = n%m;
n = temp;
}
System.out.printf("%d与%d的最大公约数是%d\n",m,n,m);
}
}
边栏推荐
猜你喜欢
无需精子卵子子宫体外培育胚胎,Cell论文作者这番话让网友们炸了
两分钟录音就可秒变语言通!火山语音音色复刻技术如何修炼而成?
AQS同步组件-FutureTask解析和用例
已解决IndentationError: unindent does not match any oute r indentation Level
Intra-group reverse order adjustment of K nodes
ViewPager fragments of nested data blank page abnormal problem analysis
你没见过的《老友记》镜头,AI给补出来了|ECCV 2022
The grep command Shell regular expressions, the three musketeers
数字化转型之支撑保障单元
中断系统结构及中断控制详解
随机推荐
Scala Advanced (7): Collection Content Summary (Part 1)
曼城推出可检测情绪的智能围巾,把球迷给整迷惑了
Use RecyclerView to implement three-level collapsed list
Report: The number of students who want to learn AI has increased by 200%, and there are not enough teachers
00后写个暑假作业,被监控成这笔样
中断系统结构及中断控制详解
Manchester city launch emotional intelligence scarf can be detected, give the fans
合并两个有序列表
Too much volume... Tencent was asked on the side that the memory was full, what would happen?
流量焦虑背后是企业对客户关系管理的不足
ABAP 面试题:如何使用 ABAP 编程语言的 System CALL 接口,直接执行 ABAP 服务器所在操作系统的 shell 命令?
无需精子卵子子宫体外培育胚胎,Cell论文作者这番话让网友们炸了
基于CAP组件实现补偿事务与幂等性保障
Rust从入门到精通04-数据类型
系统提供的堆 VS 手动改写堆
ViewPager fragments of nested data blank page abnormal problem analysis
The grep command Shell regular expressions, the three musketeers
一甲子,正青春,CCF创建六十周年庆典在苏州举行
JVM常用监控工具解释以及使用
水能自发变成“消毒水”,83岁斯坦福教授:揭示冬天容易得流感的部分原因...