Introduction
In this program we are going to solve a problem called prime number using method/function in java. And we have to take input the number from the user. Then send it to a method called isPrime() . The method will return the boolean type value and if the value is true then we print the number is prime otherwise not prime. And to check a number is prime or not we have to run a loop till square root of the given number because after the square root value it will repeat.
Following Steps
- Create a Scanner class object input . For taking input from the user.
- Now declare and integer variable num and take input from the user.
- Take if condition and call isPrime() in it . Pass the num value to isPrime(num) method.
- In the method declare a double type variable name length and put the square root value of the num.
- Now Run a for loop from 2 to length.
- if(num % i == 0) return false.
- In the end return true
- And If the num <= 1 , return false.
Java Code
package FunctionsOrMethods;
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
System.out.println("Please Enter a number for checking if it is prime of not: ");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
if (isPrime(num)){
System.out.println("The Number " + num + " is a prime number");
}
else {
System.out.println("The Number " + num + " is not a prime number");
}
}
private static boolean isPrime(int num) {
if (num <= 1){
return false;
}
double length = Math.sqrt(num);
for (int i = 2; i < length; i++) {
if (num % i == 0){
return false;
}
}
return true;
}
}
Top comments (0)