Post

Created by @nathanedwards
 at November 1st 2023, 6:29:50 pm.

Question:

Consider the following Math class methods:

public class Math {
    
    // Method to compute the factorial of a given number
    public static int factorial(int num) {
        if (num == 0) {
            return 1;
        } else {
            int result = 1;
            for (int i = 1; i <= num; i++) {
                result *= i;
            }
            return result;
        }
    }
    
    // Method to determine if a given number is prime
    public static boolean isPrime(int num) {
        if (num < 2) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }
}

Explain the purpose of each method and how they work. Additionally, provide an example usage of each method with appropriate inputs and output.

Answer:

  1. factorial(int num) method:

    The factorial() method computes the factorial of a given number. The factorial of a non-negative integer n, denoted as n!, is the product of all positive integers less than or equal to n. By convention, 0! is defined to be 1.

    This method works by using a for loop to multiply each number from 1 up to the given input num. It initializes the result to 1 and multiplies it by each value of i in the loop, updating result with the multiplication result at each iteration. Finally, it returns the computed factorial.

    Example usage:

    int factorialOfFive = Math.factorial(5);
    // The factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120
    System.out.println(factorialOfFive);  // Output: 120
    
  2. isPrime(int num) method:

    The isPrime() method determines whether a given number is prime or not. A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself. Any number less than 2 is not considered prime.

    This method works by iterating from 2 up to the square root of the input num. For each iteration, it checks if num is divisible by i without any remainder. If it finds a divisor, it returns false indicating that num is not prime. If no divisors are found, it returns true.

    Example usage:

    boolean isSeventeenPrime = Math.isPrime(17);
    System.out.println(isSeventeenPrime);  // Output: true
    
    boolean isCompositeNumPrime = Math.isPrime(25);
    System.out.println(isCompositeNumPrime);  // Output: false