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