Prime number
A prime number is an integer greater than 1 whose only factors are 1 and itself. A factor is an integer that can be divided evenly into another number.
Logic
To print the sum of all prime numbers up to N we have to iterate through each number up to the given number and check if the number is a prime or not if it is a prime number then simply sum it or add it in one temporary variable.
Once the outer loop is completed we have to print that temporary variable containing the sum of primes.
See also: Check whether a number is prime number or not
Program
import java.util.Scanner; public class SumOfPrimes { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Take input from user System.out.print("Find sum of prime numbers upto : "); int upto = scanner.nextInt(); int sum = 0; for(int num = 2; num <= upto; num++) { int i; for(i = 2; i <= (num / 2); i++) { if(num % i == 0) { i = num; break; } } // If the number is prime then add it. if(i != num) { sum += num; } } System.out.println("\nSum of all prime numbers upto " + upto + " : " + sum); } }
Output
Find sum of prime numbers upto : 50
Sum of all prime numbers upto 50 : 326