ProjectEuler 12

求第一个有500个除数因子的三角数,具体题目见原文:

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、迭代每个三角数检查因子的数目

2、一个数如果平方根不是整数,那么从1到他的平方根,找到一个因子相当于找到2个因子,可以减少一半计算

3、一个数的平方根是整数,那么平方根是他的一个因子

代码:

private static long hdt(int N) {
        long result = 1;
        for (int k = 2; numOfDivisor(result) < N; result += k, k += 1)
            ;
        return result;
    }

    private static int numOfDivisor(long n) {
        if (n < 3)
            return (int) n;
        int num = 1;
        int i;
        for (i = 2; i * i < n; i += 1) {
            if (n % i == 0) {
                num++;
//                System.out.print(i + " ");
            }
        }
        num *= 2;
        if (i * i == n) {
            num++;
//            System.out.print(i);
        }
//        System.out.println();
        return num;
    }

官网给出了两种优化了很多的解法:

第二种解法没看懂,英文不是很好也有些关系,囧~

第一种解法也有趣,一个数的因子个数等于他的质数因子的(指数+1)的乘积

比如说28=2*2*7,那么28的因子数即为(2+1)*(1+1) = 6,

很有趣的结论,不过没有真名,而且要维持一个素数数组

如果下次还要用到素数,我打算做一个txt文件保存素数表好了。。。

原文地址:https://www.cnblogs.com/lake19901126/p/3084461.html