题目
辗转相除法
运行结果:232792560
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
找出最小的能被1-20中每个数整除的数。
2520是最小的能被1-10中每个数字整除的正整数。
最小的能被1-20中每个数整除的正整数是多少?
解答:这题比较可以使用穷举法,不过时间比较长,时间大概3s左右。也可以使用辗转相除法来求两数最大公约数。最小公倍数则由这个公式来求:
GCD * LCM = 两数乘积,其中GCD是两数最大公约数,LCM是两数最小公倍数。这种方法时间不到1s;
穷举法Java程序
public class N_5 {
public static int nlcm(int n) {
int number = n;
while (true) {
boolean flag = true;
for (int i = n/ 2+1; i <= n; i++) {
if (number % i != 0) {
flag = false;
break;
}
}
if(flag)
break;
number++;
}
return number;
}
public static void main(String[] args) {
System.out.println(nlcm(20));
}
}
运行结果:232792560
辗转相除法
public class N_5 {
public static long gcd(long a ,long b)//求任意两个整数的公约数
{
if(a<b)
{
a = a + b;
b = a - b;
a = a - b;
}
long c;
while(b!=0)
{
c = a%b;
a = b;
b = c;
}
return a;
}
public static long lcm(long a,long b)//求任意两个整数的最小公倍数
{
return a*b/gcd(a,b);
}
public static long nlcm(long n)//求小于n的正整数数最小公倍数
{
if(n==0)
return 1;
return lcm(nlcm(n-1),n);
}
public static void main(String []args)
{
System.out.println(nlcm(20));
}
}
运行结果:232792560