Calculating the Sum of Prime Numbers in Java

Problem:

A prime number is a number that can only be divided by 1 and itself. The first twenty-five prime numbers are: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97. Write a program that prints the summation of all prime numbers from 2 to N where N is a value entered by the user. The output of your program should look as follows:

Output:

Please enter the value of N:
6
The sum of prime numbers from 2 to 6 is: 10

Solution:

import java.util.Scanner;
public class Problem3
{
 public static void main(String[] args)
 {
  Scanner scan=new Scanner(System.in);
  int sum=0;
  System.out.println("Please enter the value of N:");
  int N=scan.nextInt();
  for(int prime=2;prime<=N;prime++)
  {
   int numdivisors=0;
   
   for(int divisor=2;divisor<prime;divisor++)
   {
    if(prime%divisor == 0)
     numdivisors++;
   }
   
   if(numdivisors == 0)
    sum += prime;
  }
  
  System.out.printf("The sum of prime numbers from 2 to %d is: %d",N,sum);
 }
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact