Created
February 9, 2024 15:30
-
-
Save HabibulHH/eed8249bd0116bb79fc854a165935088 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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