|
-
Mar 20th, 2008, 12:14 PM
#1
Thread Starter
Addicted Member
Consecutive Integers
Im trying to solve this
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?
I wrote this code, it should work but it doesnt !
It works correctly for number under 100, but it doesnt even work for numbers under 1000
it gives a wrong answer 281 (it must be 953)
can anyone tell me where im going wrong?
Code:
public class ConescutivePrimes
{
public static boolean isPrime(int nbr)
{
boolean isNPrime=true;
for (int i = 2; i < nbr; i++)
if ((nbr != i) && (nbr % i == 0))
{
isNPrime = false;
break;
}
if (isNPrime == true) return true;
else return false;
}
public static void main(String[] args)
{
int maxValue=1000,sum=0,lastPrimeSum=0;
for (int i=2;i<maxValue;i++)
{
if (isPrime(i) == true && sum+i<maxValue)
{
sum+=i;
if (isPrime(sum)==true)
lastPrimeSum=sum;
}
}
System.out.println(lastPrimeSum);
}
}
change the value of maxValue to 100 and see the correct answer,
change it to 1000 and see it go all wrong... WHY?
Im using Visual Studio 2008 Professional Edition
.Net Framework 3.5
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|