Computer Applications
Write a program to input a number and check whether it is a prime number or not. If it is not a prime number then display the next number that is prime.
Sample Input: 14
Sample Output: 17
Java
Java Iterative Stmts
46 Likes
Answer
import java.util.Scanner;
public class KboatPrimeCheck
{
public void primeCheck() {
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int num = in.nextInt();
boolean isPrime = true;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num + " is a prime number");
}
else {
for (int newNum = num + 1; newNum <= Integer.MAX_VALUE; newNum++) {
isPrime = true;
for (int i = 2; i <= newNum / 2; i++) {
if (newNum % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println("Next prime number = " + newNum);
break;
}
}
}
}
}
Variable Description Table
Program Explanation
Output
Answered By
12 Likes
Related Questions
A number is said to be Duck if the digit zero is (0) present in it. Write a program to accept a number and check whether the number is Duck or not. The program displays the message accordingly. (The number must not begin with zero)
Sample Input: 5063
Sample Output: It is a Duck number.
Sample Input: 7453
Sample Output: It is not a Duck number.Write a program to input a number and check and print whether it is a Pronic number or not. [Pronic number is the number which is the product of two consecutive integers.]
Examples:
12 = 3 * 4
20 = 4 * 5
42 = 6 * 7Write a program to input a number and display it into its Binary equivalent.
Sample Input: (21)10
Sample Output: (10101)2A prime number is said to be 'Twisted Prime', if the new number obtained after reversing the digits is also a prime number. Write a program to accept a number and check whether the number is 'Twisted Prime' or not.
Sample Input: 167
Sample Output: 761
167 is a 'Twisted Prime'.