java - 欧拉计划的错误答案 50

标签 java algorithm numbers

我正在尝试欧拉项目的问题 50。

The prime 41, can be written as the sum of six consecutive primes:

41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes?

这是我的代码:

    public class consPrime
    {
        static int checker(int ar[],int num,int index) //returns no.of consecutive
        {                                              //primes for the given num  
            while(true)
        {

        int temp=num;

        for(int i=index;i>=0;i--)
        {
            temp=temp-ar[i];

            if(temp==0)
            {
                return (index-i+1);
            }               
        }           
        index--;
        if(index==0)
        return 0;           
        }
    }

    public static void main(String args[])
    {               
        int n=100000;
        int ar[]=new int[n];
        int total=0;int flag;

        for(int i=2;i<1000000;i++)   //Generates an array of primes below 1 million
        {
            flag=1;

            for(int j=2;j<=Math.sqrt(i);j++)
            {
                if(i%j==0)
                {
                    flag=0;
                    break;
                }                   
            }
            if(flag==1)
            {
                ar[total]=i;
                total++;
            }               
        }

        int m=0;
        int Big=0;

        for(int i=total;i>=0;i--) //Prints the current answer with no.of prime
        {
            m=checker(ar,ar[i],i-1);
            if(Big<=m)
            {Big=m;
                System.out.println(ar[i]+"     "+Big);
            }
        }           
    }       
}

基本上它只是创建一个包含最多 1000000 个素数的 vector ,然后循环遍历它们以找到正确的答案。答案是 997651,计数应该是 543,但我的程序分别输出 990707 和 75175。可能出了什么问题?

最佳答案

几个大问题:

  1. 先解决一些小问题:学会正确缩进代码,学会使用正确的命名约定。在 Java 中,变量名称使用驼峰式大小写,而类型名称使用 PascalCasing。

  2. 您的逻辑中有很多问题:您遍历素数数组,直到达到零或直到遍历数组中的所有数字。但是,请注意,整数存在下溢/上溢。 “温度”有可能不断减去,变成负数,变成正数等等,最后达到零。然而这不是正确答案

  3. 您只尝试查找以索引 - 1 结尾的连续数字。例如,要检查索引 10 处的素数,您要从索引 9 向后查找连续素数。然而,直到你的目标数字的连续素数总和很少(事实上几乎从来没有,除了 5)包含“前一个”素数。整个逻辑完全错误。

  4. 更不用说您为检查器传递的错误参数,用户@pm-77-1 的评论中提到了这一点

关于java - 欧拉计划的错误答案 50,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15777118/

相关文章:

algorithm - Shor 的算法可以用于 key 加密吗?

algorithm - 从图中删除边后如何更新MST?

algorithm - 自由移动的球体何时可以逃离由一组不可通过的坐标定义的 ‘cage’?

javascript - Javascript中的排序方法在for循环中不起作用吗?

function - 将代表软件版本的两个数字与几个点进行比较

java - 增强的 for 循环编译适用于 JDK 8 但不是 7

java - 在maven中,如何在发布版本中命名与快照构建中不同的war文件

java - 如何从子类的子类获取在父类(super class)中实例化的对象的字段

algorithm - 将数字编码为单个数字

java - New Relic MySQL 服务器未显示