Write a program to add all primes from one to hundreds

What is wrong in my code?

Expected Conclusion = 1060

I checked with the sum of 1000 primes. It will display output 3682913 correctly

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;
        }
    }
+4
source share
3 answers

Currently, you are counting the first 100 primes, not the primes found in the range 1 - 100. Here you can completely lose the value of the counter.

Your code can be simplified as such by using a for loop instead of going from 2 to 100 (1 is 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;
    }
}
+1
source

You count up to 100 primes , but not up to 100 numbers .

, while 100 .

:

int number = 2;
      int count = 0;
      long sum = 0;
      while(number <= 100){ 
          if(isPrimeNumber(number)){
              sum += number;
              count++;
          }
          number++;
      }
      System.out.println(sum);
  }

1060.

+5

You can use the code below to find the sum of the first primes from 1 to 100. This will give you the correct result.

public class PrimeNumber {
    public static void main(String args[]){
        int number = 2;
        int sum = 0;
        while(number <= 100){ 
            if(isPrimeNumber(number)){
                sum += number;
            }
            number++;
        }
        System.out.println(sum);
    }

    private static boolean isPrimeNumber(int number){
        int sqrt = (int) Math.floor(Math.sqrt(number));
        for(int i = 2; i <= sqrt; i++){
            if(number % i == 0){
                return false;
            }
        }
        return true;
    }
}
+1
source

Source: https://habr.com/ru/post/1649572/


All Articles