Ramasamy Ramasamy - 4 months ago 16
Java Question

write a program to add all the prime numbers from one to hundred

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;
}
}

Answer

Currently, you are counting the first 100 primes, not the primes found in the range 1 - 100. You can lose the count variable entirely here.

Your code can be simplifed as such, using a for loop instead to go from 2 to 100 (1 not included, of course)...

public class PrimeNumber {
    public static void main(String args[]) {
        long sum = 0;
        for (int number = 2; number <= 100; number++) {
            if (isPrimeNumber(number)) {
                sum += 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;
    }
}
Comments