How to Find Out if a Number Is Prime in Java That Returns a Boolean

A prime number is a number that is only divisible by itself or one. To determine if a number is a prime number in Java, you divide the number programmatically by two through nine. If the remainder is zero after these calculations, the number is not a prime number. You can then return the boolean value "false" in the function and "true" if every calculation results in a remainder.

Instructions

    • 1

      Open your Java editor and open the Java file you want to use to create the Java function. Type the following code to create the Java function:

      public bool primeNumber(int number) {

      }

      Type the function code within the curly brackets.

    • 2

      Create the variables you need to perform the calculations. The following code creates the variable used to contain the remainder of the division and a variable to set the function to "true" or "false:"

      decimal result = 0;
      bool isPrime = true;

    • 3

      Create the loop to divide the number by two through nine. The following code divides the number by each number, returns the remainder, and sets the boolean value to "false" if a remainder is any number except zero:

      for (int i = 2; i < 10; i++) {
      result = number % i;
      if (result != 0 ) //the number is not a prime number
      {
      isPrime = false;
      }
      }

    • 4

      Return the boolean result in the function:

      return isPrime;

Related Searches:

References

Comments

Related Ads

Featured