DEV Community

Cover image for 🧑‍💻Define a method to find out if a number is prime or not.
Tahzib Mahmud Rifat
Tahzib Mahmud Rifat

Posted on

🧑‍💻Define a method to find out if a number is prime or not.

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

  1. Create a Scanner class object input . For taking input from the user.
  2. Now declare and integer variable num and take input from the user.
  3. Take if condition and call isPrime() in it . Pass the num value to isPrime(num) method.
  4. In the method declare a double type variable name length and put the square root value of the num.
  5. Now Run a for loop from 2 to length.
  6. if(num % i == 0) return false.
  7. In the end return true
  8. 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;
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

Image description

Top comments (0)