Home » Sum of Prime Numbers in Java

Sum of Prime Numbers in Java

by Online Tutorials Library

Sum of Prime Numbers in Java

In this section, we will create Java programs to find the sum of all the prime numbers in a given range. Before moving ahead in this section, let’s see the important facts about prime numbers.

  • A prime number is a number that is greater than 1 and can be divided by 1 and itself without leaving a remainder.
  • The numbers 0 and 1 are not prime numbers.
  • The only even prime number is 2. All other even numbers are divisible by 2.

Steps to Find the Sum of Prime Numbers

  • Read or initialize the lower and upper limit.
  • Iterate a loop (for or while) to find the prime numbers between the given range.
  • If the number is prime, add that number to the variable sum and print the result.

Let’s implement the above steps in a Java program.

Java Program to Find the Sum of Prime Numbers

There are the following ways to find the sum of prime numbers:

Let’s create the Java program for each.

Using for Loop

SumOfPrimeNumbersExample1.java

Output:

The Sum of Prime Numbers from 1 to 200 is: 4227  

Using while Loop

In the following program, we have used a while loop instead of for loop. The logic is the same as above.

SumOfPrimeNumbersExample2.java

Output:

The Sum of Prime Numbers from 1 to 100 is: 1060  

Using Function

SumOfPrimeNumbersExample3.java

Output:

The sum of all the prime number between the given range is: 328  

Using Dynamic Programming

The logic for the sum of prime numbers using dynamic programming is a bit tricky and difficult to implement. In this approach, we will use arrays. Let’s see the steps.

  1. Declare two arrays number[] and array[].
  2. Initialize array[] to 0.
  3. Iterate over the for loop till sqrt(uprlimit). If the array element is 0, consider it as prime and its multiple as non-prime. While marking the non-prime numbers, set the respective location to 1.
  4. Update the number[] array that holds the sum of prime numbers. Each position of number[i] represents the sum of all prime numbers within a specified range i.e. [1, i].

Let’s implement the above steps in a Java program.

SumOfPrimeNumbersExample4.java

Output:

The sum of all the prime number between the given range is: 75067  

You may also like