What is wrong in my code?
Expected output=1060
I checked with 1000 prime numbers sum. It will show correctly output 3682913
public class PrimeNumber {
public static void main(String args[]){
int number = 2;
int count = 0;
long sum = 0;
while(count <100){
if(isPrimeNumber(number)){
sum += number;
count++;
}
number++;
}
System.out.println(sum);
}
private static boolean isPrimeNumber(int number){
for(int i=2; i<=number/2; i++){
if(number % i == 0){
return false;
}
}
return true;
}
}
You are counting up to 100 primes but not up to 100 numbers.
So your while loop should run up to 100 numbers.
This should be your main method:
int number = 2;
int count = 0;
long sum = 0;
while(number <= 100){
if(isPrimeNumber(number)){
sum += number;
count++;
}
number++;
}
System.out.println(sum);
}
This would give your output 1060.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With