Java: Compute the sum of first n given prime numbers
Java Basic: Exercise-232 with Solution
Sum of First n Prime Numbers
Write a Java program to compute the sum of the first n prime numbers.
Input:
n ( n ≤ 10000). Input 0 to exit the program.
Visual Presentation:
Sample Solution:
Java Code:
// Importing necessary classes for input/output operations and mathematical functions
import java.util.*;
// Main class named "Main"
public class Main {
// Main method to execute the program, throws IOException
public static void main(String[] args) throws java.io.IOException {
// Creating Scanner object to read input from the user
Scanner scan = new Scanner(System.in);
// Initializing variables to count prime numbers and calculate their sum
int count = 0;
int sum = 0;
// Prompting the user to input a number (n<=10000) to compute the sum
System.out.println("Input a number (n<=10000) to compute the sum:");
// Reading the input number
int n = scan.nextInt();
// Looping through numbers to find prime numbers and calculate their sum
for (int i = 2;; i++) {
if (prime(i)) {
count++;
sum += i;
// Breaking the loop when the required number of prime numbers is reached
if (count == n) break;
}
}
// Outputting the sum of the first n prime numbers
System.out.println("Sum of first " + n + " prime numbers:");
System.out.println(sum);
}
// Method to check if a number is prime
public static boolean prime(int n) {
// If n is 1, it is not prime
if (n == 1) return false;
// Checking for factors up to the square root of n
for (int i = 2; i <= Math.sqrt(n); i++)
if (n % i == 0) return false;
// If no factors are found, n is prime
return true;
}
}
Sample Output:
Input a number (n<=10000) to compute the sum: 100 Sum of first 100 prime numbers: 24133
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to find the difference between the largest integer and the smallest integer which are created by 8 numbers from 0 to 9. The number that can be rearranged shall start with 0 as in 00135668.
Next: Write a Java program that accept a even number (n should be greater than or equal to 4 and less than or equal to 50,000, Goldbach number) from the user and create a combinations that express the given number as a sum of two prime numbers. Print the number of combinations.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/basic/java-basic-exercise-232.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics