歐拉計劃 第5題

題目

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章