版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hpdlzu80100/article/details/85228095
Our life is frittered away by detail ... Simplify, simplify.
by Henry Thoreau
(美国哲学家亨利·梭罗说,我们的生活被琐碎的细节消磨殆尽,要简化,要简化!)
所以,如果能够找到现成的解决方案,我们就没必要自己埋头研究算法了(除非我们的目的在于研究算法本身!)。
package exercises.ch6Methods;
import java.util.*;
//JHTP Exercise 6.27 (Greatest Common Divisor)
//by [email protected]
/**
*
*6.27 (Greatest Common Divisor) The greatest common divisor (GCD) of two integers is the
*largest integer that evenly divides each of the two numbers. Write a method gcd that
*returns the greatest common divisor of two integers. [Hint: You might want to use Euclid’s algorithm.
*You can find information about it at en.wikipedia.org/wiki/Euclidean_algorithm.] Incorporate the method
*into an application that reads two values from the user and displays the result.
*
*/
public class GreatedCommonDivisor {
//此算法基于本人2008年的求最大公约数的方法,https://blog.csdn.net/hpdlzu80100/article/details/2290499
public static long gcd1(long n1, long n2) {
long g = 0;
for(long i=1;i<=Math.min(n1,n2);i++)
{
if (n1 % i == 0 && n2 % i == 0)
g = i;
}
return g;
}
//此算法https://blog.csdn.net/jiaolipe/article/details/1476068,采用了Euclid’s algorithm(欧几里得算法)
private static long gcd2 (long num1, long num2){
while (num1 != num2)
{
if (num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
}
return num1;
}
public static void main(String args[]) {
long number1;
long number2;
long gcd1;
long gcd2;
Scanner scan=new Scanner(System.in);
do {
System.out.printf("请输入第一个整数(输入-1退出):");
number1 = scan.nextLong();
if(number1 == -1)
{System.out.print("已退出程序。");
break;
}
System.out.printf("请输入第二个整数(输入-1退出):");
number2 = scan.nextLong();
if(number2 == -1)
{System.out.print("已退出程序。");
break;
}
long beginTime=System.nanoTime();
gcd1 = gcd1(number1, number2);
long endTime=System.nanoTime();
double duration1=(double)(endTime-beginTime);
System.out.printf("方法1:%d和%d的最大公约数为:%d,共用时%f纳秒%n", number1, number2, gcd1, duration1);
beginTime=System.nanoTime();
gcd2 = gcd2(number1, number2);
endTime=System.nanoTime();
double duration2=(double)(endTime-beginTime);
System.out.printf("方法2:%d和%d的最大公约数为:%d,共用时%f纳秒%n", number1, number2, gcd2, duration2);
System.out.printf("方法2的用时是方法1的%.2f%%%n", duration2/duration1 * 100);
System.out.println();
} while (number1 != -1);
System.out.println("已退出程序。");
scan.close();
}
}
运行结果:
请输入第一个整数(输入-1退出):6666 请输入第二个整数(输入-1退出):9999 方法1:6666和9999的最大公约数为:3333,共用时701450.000000纳秒 方法2:6666和9999的最大公约数为:3333,共用时9078.000000纳秒 方法2的用时是方法1的1.29%
扫描二维码关注公众号,回复:
4713778 查看本文章
请输入第一个整数(输入-1退出):34567 请输入第二个整数(输入-1退出):3456 方法1:34567和3456的最大公约数为:1,共用时415659.000000纳秒 方法2:34567和3456的最大公约数为:1,共用时13421.000000纳秒 方法2的用时是方法1的3.23% |