【问题标题】:Finding the first triangle number with more than 500 divisors找到第一个超过 500 个除数的三角形数
【发布时间】:2018-09-09 21:31:41
【问题描述】:

我正在尝试解决 Java 中的第 12 个欧拉问题,但我似乎真的无法理解这里的问题。该脚本旨在输出具有 500 多个除数的第一个三角形数,如代码中的注释中所述。正确答案应该是“76576500”,而我的脚本输出的答案是“842161320”——相差很大。有谁知道我哪里出错了?感谢所有帮助,谢谢!

public class Script_012
{
/*
    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?
*/
public static void main (String [] args)
{
    boolean enough_factors = false;
    long num = 1;
    long runner = 1;
    int num_of_factors;
    int highest_factors = 0;
    while (!enough_factors)
    {
        num_of_factors = 0;
        for (int i = 1; i < (int) Math.sqrt(num); i ++)
        {
            if ((num % i) == 0)
            {
                num_of_factors += 1;
            }
        }
        if (num_of_factors > 500)
        {
            enough_factors = true;
            System.out.println(num);
        }
        runner += 1;
        num += runner;
    }
}
}

【问题讨论】:

    标签: java factors


    【解决方案1】:

    问题在于您只是添加小于或等于平方根的因子,但问题是讨论所有因子,包括大于平方根的因子。

    简单(但缓慢)的解决方案:

    for (int i = 1; i &lt; (int) Math.sqrt(num); i ++) 更改为for (int i = 1; i &lt;= num; i ++)

    更好的解决方案: 保持 for 循环的迭代次数相同,但每次加 2,并仅考虑平方根为一个因素。 代码:

    public static void main (String [] args)
    {
        boolean enough_factors = false;
        long num = 1;
        long runner = 1;
        int num_of_factors;
        int highest_factors = 0;
        while (!enough_factors)
        {
            num_of_factors = 0;
            for (int i = 1; i < (int) Math.sqrt(num); i ++)
            {
                if ((num % i) == 0)
                {
                    num_of_factors += 2;
                }
            }
    
            if(num % Math.sqrt(num) == 0) {
                num_of_factors++;
            }
    
            if (num_of_factors > 500)
            {
                enough_factors = true;
                System.out.println(num);
            }
            runner += 1;
            num += runner;
        }
    }
    

    【讨论】:

    • 完美,谢谢。我知道这将与使用 Math.sqrt 而不是循环遍历 num 有关,但在我的笔记本电脑上花费的时间太长了。
    猜你喜欢
    • 2018-03-17
    • 2013-03-22
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多