永发信息网

java 辗转相除法求最大公约数

答案:5  悬赏:80  手机版
解决时间 2021-03-27 20:24
  • 提问者网友:两耳就是菩提
  • 2021-03-27 10:13
java 辗转相除法求最大公约数
最佳答案
  • 五星知识达人网友:孤独的牧羊人
  • 2021-03-27 11:49
比较好用的是辗转相除法。
比如:49和91
a b temp
49 % 91 = 49
91 % 49 = 42
49 % 42 = 7
42 % 7 = 0
所以最大公约数就是7.

public class T {
public static void main(String[] args) {
int gcd = gcd(91, 49);
System.out.println(gcd);
}


public static int gcd(int a, int b) {
while(b != 0) {
int temp = a%b;
a = b;
b = temp;
}
return a;
}

}
全部回答
  • 1楼网友:妄饮晩冬酒
  • 2021-03-27 16:28
不知道
  • 2楼网友:长青诗
  • 2021-03-27 15:09
//经编译后改正错误后正确运行
import java.util.ArrayList;
import java.util.List;
import java.io.*;
public class maxinterger{
public static void main(String args[])throws IOException{
Integer shu1 = 0;
Integer shu2 = 0;
int t = 0;
//Vectorpool = new ();
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入第一个正整数");
shu1 = (new Integer(stdin.readLine()));
System.out.println("请输入第二个正整数");
shu2 = (new Integer(stdin.readLine()));
t = divisor(shu1,shu2);
System.out.println(t);
}
public static int divisor(int a,int b){ //此行没有设置返回类型
if(a int m = 0;
m = a;
a = b;
b = m;
}
int k;
k = a%b;
if(k == 0){
return b;
}else{
a = b;
b = k;
divisor(a,b);
}
return b;//这行没有加返回值
}
}追问你输入24、9,的出来的最大公约数竟然是6,不知道方法哪里不对了!??
  • 3楼网友:十年萤火照君眠
  • 2021-03-27 14:05
package example_4;
import java.util.ArrayList;
import java.util.List;
import java.io.*;
public class QuickSort{
public static void main(String args[])throws IOException{
Integer shu1 = 0;
Integer shu2 = 0;
int t = 0;
//Vectorpool = new ();
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入第一个正整数");
shu1 = (new Integer(stdin.readLine()));
System.out.println("请输入第二个正整数");
shu2 = (new Integer(stdin.readLine()));
t = divisor(shu1,shu2);
System.out.println(t);
}
public static int divisor(int a,int b){
if(a int m = 0;
m = a;
a = b;
b = m;
}
int k;
k = a%b;
if(k == 0){
return b;
// break;
}else{
a = b;
b = k;
divisor(a,b);
}
return k;
}
}
  • 4楼网友:琴狂剑也妄
  • 2021-03-27 12:38
辗转相除不是最基础的算法嘛?!我给你:
public static int divisor(int a,int b)
{
if(a {
int c=a;
a=b;
b=c;
}
if(b==0)
return a;
else
return divisor(a-b,b);
}
这不是很简单的东西嘛!
具体原理高中数学课本上就有的。
以24和9为例:
divisor(24,9)=divisor(15,9)=divisor(6,9)=divisor(3,6)=divisor(6,3)=divisor(3,3)=divisor(0,3)=divisor(3,0)=3
正确了。
亲手写的,
望采纳!
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯