KnowledgeBoat Logo

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

45 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

BlueJ output of 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

Answered By

12 Likes


Related Questions