Check the number is Prime using Java - Technical Interview - MNC - 2024
Check the number is Prime
First we need to check whether the number is 1 or 0, if it is straight away you can say it is Prime Number.
Next we need to divide the number by 2, because if we couldn't divide a number by more than half of a number.
Final Thing is start the for loop and inside for loop modules the given number by loop variable, if the remainder is zero it is not Prime, if not it is Prime Number.
Code :
package com.dinatechy.challange;
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
//Check if the given number is Prime or not
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
scan.close();
boolean result = isPrime(number);
System.out.println( result ? "Yes it is" : "No it's not" );
}
public static boolean isPrime(int num) {
// a number is divisible by own or 1
if(0 == num || 1 == num)
return true;
// 5/2 = 4.5 -> 5/3
for(int i=2; i<num/2; i++) {
if( num % i == 0 ) {
return false;
}
}
return true;
}
}
Input : 13
Output :
Yes it is
Follow us for more useful Code....
Comments
Post a Comment