ProjectEluer - 12

问题:

Highly divisible triangular number

Problem 12

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

Let us list the factors of the first seven triangle numbers:

 1: 1
 3: 1,3
 6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors?

翻译:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...这样的序列是三角数,规律是第n个数等于1+2+3+...+n的和。数列中除数个数大于5的第一个数是28,求除数个数大于500的第一个数?


代码:

package projectEuler;

public class Problem12 {
	private static final int COUNT = 500;
	public static void main(String[] args) {
		long sum=0;
		int i=1;
		while(true){
			sum += i;
			if(COUNT < getNumberOfDivisor(sum)){
				System.out.println("sum:"+sum);
				break;
			}
			i++;
		}
		System.out.println("end");
	}
	
	static int getNumberOfDivisor(long num){
		int total = 0;
		for(int i=2; i<Math.sqrt(num); i++){
			if(num%i == 0){
				total += 2;
			}
		}
		return total+2;
	}

}

关键函数是求一个数有多少个除数getNumberOfDivisor(); 当然你可以从2开始一直算,直到除数等于被除数,但是这样效率很低。另外一个方法是:如果你求得一个除数,那么除得的商也一定是其中一个除数,所以每次统计的时候可以加2,那么需要遍历的范围就是 小于sqrt(num)。

你可能感兴趣的:(算法,欧拉项目)