Arrays & Hashing

Math Chall

Estimated reading: 1 minute 40 views

Write a function MathChallenge(num1, num2) that takes two numbers as input and returns their Greatest Common Divisor (GCD). This is the largest number that divides both numbers evenly (with no remainder). The input range for both parameters will be from 1 to 10310^3.

  • Example 1:
    Input: num1 = 7, num2 = 3
    Output: 1

  • Example 2:
    Input: num1 = 36, num2 = 54
    Output: 18

				
					public class MathChallenge {

    // Function to find the GCD of two numbers using the Euclidean algorithm
    public static int gcd(int num1, int num2) {
        while (num2 != 0) {
            int temp = num2;
            num2 = num1 % num2;
            num1 = temp;
        }
        return num1;
    }

    public static void main(String[] args) {
        // Test cases
        System.out.println(gcd(7, 3));   // Expected Output: 1
        System.out.println(gcd(36, 54)); // Expected Output: 18
        System.out.println(gcd(12, 16)); // Expected Output: 4
        System.out.println(gcd(100, 25)); // Expected Output: 25
    }
}

				
			
Share this Doc

Math Chall

Or copy link

CONTENTS