
saxenadivya859
Wednesday, 2024-08-21
Prime numbers are integers greater than 1 that have no divisors other than 1 and themselves. They are fundamental in number theory and have applications in cryptography, computer algorithms, and more. In this article, weβll discuss how to add two prime numbers in Java, ensuring both inputs are prime before performing the addition.
Hereβs a simple Java program that performs these tasks:
java
Copy code
import java.util.Scanner;
public class AddPrimeNumbers {
// Function to check if a number is prime
public 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;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input two numbers
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
// Check if both numbers are prime
if (isPrime(num1) && isPrime(num2)) {
int sum = num1 + num2;
System.out.println("The sum of the two prime numbers is: " + sum);
} else {
System.out.println("Both numbers must be prime.");
}
scanner.close();
}
}
false, indicating the number is not prime. Otherwise, it returns true.main method, the program takes two numbers as input from the user. It checks if both numbers are prime using the isPrime function. If they are prime, the program adds them and displays the sum. If not, it informs the user that both numbers must be prime.This Java program is a simple yet effective way to ensure that the numbers you are adding are prime. The core logic revolves around checking the primality of numbers, which is an essential concept in many computational problems. By understanding and using this code, you can apply similar logic to more complex problems involving prime numbers