我在嘗試歐拉項目的問題50。對於歐拉項目50的錯誤答案
的首要41,可以寫爲六個連續的素數的總和:
41 = 2 + 3 + 5 + 7 + 11 + 13這是連續 質數的最長總和,增加了低於一百的素數。 連續質數低於1000的連續素數加上素數,包含 21項,並且等於953.哪一個素數低於100萬,可以是 寫成最連續的素數之和?
這裏是我的代碼:
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的載體中,然後通過他們找到循環的正確答案。答案是997651,計數應該是543,但我的程序分別輸出990707和75175。什麼可能是錯的?
您是否已驗證您的素數數組是否已正確生成?你有沒有證實你的'checker'方法是按照你的意圖工作的?這個問題需要縮小。 – Vulcan
我不確定你的程序如何工作。在這個循環中:'for(int i = total; i> = 0; i - )'當'i'變爲0時,對'checker'的調用將'-1'作爲'index'傳遞。然後在'checker'方法中,這個循環對於(int i = index; i> = 0; i - )'以'-1'開始,並且你試圖檢索'ar [-1]'。你不是在這個時候遇到了「超出界限」的例外嗎? –
當我運行程序時,沒有錯誤......它工作正常......但顯然會產生錯誤的答案! – KayEs