Prime Number Sum Is PrimeNumber
Write A Program To Test Sum Of The
Prime Numbers Is Also Prime Number Or Not Upto N ?
package Programs;
import
java.util.Scanner;
public class
PrimeNumberSumIsPrimeNumber
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a
number (n): ");
int n = scanner.nextInt();
int sum = 0;
System.out.println("Prime
numbers up to " + n + ":");
for (int i = 2; i <= n; i++)
{
if (isPrime(i))
{
System.out.print(i + ", ");
sum += i;
}
}
System.out.println("\nSum of
prime numbers up to " + n + ": " + sum);
if (isPrime(sum))
{
System.out.println("The sum
of prime numbers (" + sum + ") is also a prime number.");
} else
{
System.out.println("The sum
of prime numbers (" + sum + ") is not a prime number.");
}
}
public static boolean isPrime(int num)
{
if (num <= 1)
{
return false;
}
// Check from 2 to the square root of
the number if there are any divisors.
for (int i = 2; i * i <= num; i++)
{
if (num % i == 0)
{
return false;
}
}
return true;
}
}
Output
Enter a number (n): 99
Prime numbers up to 99:
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,
Sum of prime numbers up to 99: 1060
The sum of prime numbers (1060) is not a prime number.
Explanation:
1. The isPrime method checks if a number is prime by iterating from 2 up to the square root of the number. If the number is divisible by any integer in this range, it is not a prime number, and the method returns false. Otherwise, it returns true.2. The sumOfPrimes method calculates the sum of all prime numbers up to the given number 'N'. It iterates from 2 to 'N', and for each number, it checks if it is prime using the isPrime method. If it is prime, the number is added to the sum variable.
3. The isPrimeNumber method is a wrapper around the isPrime method to check if a given number is prime. It handles the case where the number is less than or equal to 1 and returns false in such cases.
4. In the main method, you can change the value of 'N' to any positive integer to find the sum of prime numbers up to that number. The program then prints the sum of prime numbers and whether that sum is a prime number or not.
Comments
Post a Comment