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

Retry later

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.