一个简单的小算法来获取两个数的最大公约数, public class Test { public static void main(String[] args) { long result = gcd(15, 3); System.out.println(result); } public static long gcd(long m, long n) { while (n != 0) { long rem = m % n; m = n; n = rem; } return m; } }
获得两个随机数(100以内),并放入数组中 public int[] getTwoRandom(){ int[] t = new int[2]; Random rand = new Random(); for(int i=0;i<t.length;i++) { t[i] = rand.nextInt(100); } return t; } 1.一般算法,连续整数检测法即从m和n中比较小的数开始一次遍历整数,如果有出现可以同时被m和n整除的数,就是最大公约数 //连续整数检测法 public in
两个数的最大公约数:不能大于两个数中的最小值,算法口诀:小的给大的,余数给小的,整除返回小的,即最大公约数,(res=max%min)==0? max=min,min=res return min; 两个数的最小公倍数:等于两数之和除以两个数的最大公约数 a*b/(LCM(a,b)); #include <iostream> using namespace std; /*求最大公约数,辗转相除法来求最小公倍数*/ int getLCM(int a, int b) { int max = (a
求两个数 p 和 q 的最大公约数(greatest common divisor,gcd),利用性质 如果 p > q, p 和 q 的最大公约数 = q 和 (p % q)的最大公约数. 证明:见 http://blog.csdn.net/niushuai666/article/details/7278027 public class Euclid{ // recursive inplementation public static int gcd(int p, int q){ if(q =