Given a number x, find the smallest prime number which is greater than x.

Given a number x, find the smallest prime number which is greater than x.

Ques:- Given a number x, find the smallest prime number which is greater than x.
3 2817

3 Answers on this Question

  1. # Python3 implementation of the approach
    import math

    # Function that returns True if n
    # is prime else returns False
    def isPrime(n):

    # Corner cases
    if(n <= 1):
    return False
    if(n <= 3):
    return True

    # This is checked so that we can skip
    # middle five numbers in below loop
    if(n % 2 == 0 or n % 3 == 0):
    return False

    for i in range(5,int(math.sqrt(n) + 1), 6):
    if(n % i == 0 or n % (i + 2) == 0):
    return False

    return True

    # Function to return the smallest
    # prime number greater than N
    def nextPrime(N):

    # Base case
    if (N <= 1):
    return 2

    prime = N
    found = False

    # Loop continuously until isPrime returns
    # True for a number lower than n
    while(not found):
    prime = prime – 1 # if i use prime =prime+1 will get greater than n number.

    if(isPrime(prime) == True):
    found = True

    return prime

    # Driver code
    N = 20
    print(nextPrime(N))

    # This code is contributed by ajay

    #the output will be 19

  2. import java.util.*;
    public class Main

    {
    public static boolean isprime(int n)
    {
    int i,j=0;
    for(i=1;i<=n/2;i++)
    {
    if(n%i==0)
    {
    j++;

    }
    }
    if(j==1)
    {
    return true;

    }
    else
    {
    return false;
    }

    }
    public static void isprim(int x)
    {
    int n=x+1;
    while(true){
    if(isprime(n))
    {
    break;
    }
    n++;
    }
    System.out.println(n);
    }
    public static void main(String[] args) {
    Scanner sc =new Scanner(System.in);
    System.out.println("enter number x");
    int x=sc.nextInt();
    isprim(x);
    }
    }

  3. x=153
    y=x*2
    arr=[]
    for(i=x+1; i<y;i++){
    temp=true
    for(j=2; j<i;j++){

    if(i%j==0){
    temp=false
    }

    }
    if(temp==true){
    arr.push(i)
    }
    }
    console.log(arr[0]);

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top