Skip to content

Instantly share code, notes, and snippets.

@HabibulHH
Created February 9, 2024 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HabibulHH/eed8249bd0116bb79fc854a165935088 to your computer and use it in GitHub Desktop.
Save HabibulHH/eed8249bd0116bb79fc854a165935088 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
public class SumOfFirstNPrimes {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = scanner.nextInt();
int sum = 0;
int count = 0;
int num = 2; // Start checking from the first prime number
while (count < n) {
if (isPrime(num)) {
sum += num;
count++;
}
num++;
}
System.out.println("Sum of the first " + n + " prime numbers: " + sum);
}
// Function to check if a number is prime
private static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment