Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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;
        }
    }
like image 907
Ramasamy Avatar asked Mar 11 '23 14:03

Ramasamy


1 Answers

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.

like image 97
Pritam Banerjee Avatar answered Apr 06 '23 18:04

Pritam Banerjee