Impact-Site-Verification: dbe48ff9-4514-40fe-8cc0-70131430799e

## Search This Blog

Find nearest prime number less than input number
Problem Statement:

Find nearest prime number less than input number.
For example: if the input number is 125, then the nearest prime number which is less than this number is 113.
Be careful, in that 1 is not a prime number. So there is NO prime less than 2.
Input : n = 10
Output: 7
Input : n = 17
Output: 13
Input : n = 30
Output: 29

Algorithm:

A simple solution for this problem is to iterate from n-1 to 2, and for every number, and check whether that number is prime or not. If prime, then return it and break the loop.
MATLAB CODE:

clc
clear all
close all
x=input('Enter the number');
m=0;
c=x;
if(x>2)
while m==0
dt=0;
c=c-1;
for i=2:c-1
if(rem(c,i)==0)
dt=dt+1;
end
end
if(dt==0)
m=1;
else
m=0;
end
end
disp(c)
else
disp('There is no prime number below 2');
end

Explanation:

Sample Output:

JAVA CODE:

import java.util.Scanner;
class Qam
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
System.out.println("Enter  number:");
int x=obj.nextInt();
int m=0;
int c=x;
if(x>2)
{
while (m==0)
{
int dt=0;
c=c-1;
for(int i=2;i<=c-1;i++)
{
if((c%i)==0)
{
dt=dt+1;
}
}
if(dt==0)
{
m=1;
}
else
{
m=0;
}
}
System.out.println();
System.out.println("Nearest prime less than given number"+c);
}
else
{
System.out.println("There is no prime number below 2");
}
}

}

Sample Output:

Try with other input cases :-)