我正在尝试使用欧几里德算法来找到两个数字的GCD。欧几里德算法表示你将大数除以小数并取出余数并将原始小数除以余数,然后继续这样做直到你得到零。我的程序打印出余数和小数字,但我想找到GCD并打印出每一步(每个数字都通过程序)。
import java.util.Scanner;
import java.util.Random;
public class GCD{
public static void main(String [] args){
Scanner reader = new Scanner(System.in);
double n1;
double n2;
double firstOperation;
double smallNum;
double nextOperation;
System.out.println("Enter the first number (positive) ");
n1 = reader.nextDouble();
System.out.println("Enter the second number (positive)");
n2 = reader.nextDouble();
if (n1 > n2){
smallNum = n2;
firstOperation = n1 % n2;
System.out.println (firstOperation);
}
if (n1<n2){
smallNum = n1;
firstOperation = n2 % n1;
System.out.println (firstOperation);
}
while (firstOperation >0)
nextOperation = smallNum % firstOperation ;
//System.out.println(nextOperation);
}
}
}
答案 0 :(得分:0)
public static int gcd(int a, int b) {
System.out.println(String.format("Calculating GCD of %d and %d", a, b));
if(b == 0) {
return a;
}
return gcd(b, a % b);
}