Problem: 2.4


 Question2.4:Given an integer, create a function that returns the next prime. If the number is prime, return the number itself.

Examples

nextPrime(12) ➞ 13

nextPrime(24) ➞ 29

nextPrime(11) ➞ 11

// 11 is a prime, so we return the number itself.


Solution:

package com.company;
import java.util.Scanner;
public class lab2problem04 {
    static void  nextPrime(int n) {
        for (int i = n; i <= 400; i++) {
            int c = 0;

            for (int j = 2; j <= i; j++) {

                if (i % j == 0) {
                    c++;
                }
            }

            if (c < 2) {

                System.out.println(i);
               break;
            }


        }

    }


        public static void main (String[]args){
            Scanner Obj = new Scanner(System.in);

            System.out.println("Input fist number: ");
            int m = Obj.nextInt();
           nextPrime(m);


        }
    }



Previous Post Next Post