You are given an integer n. Your task is to compute the GCD (greatest common divisor) of two values:
sumOdd: the sum of the smallest n positive odd numbers.
sumEven: the sum of the smallest n positive even numbers.
Return the GCD of sumOdd and sumEven.
Example 1:
Input: n = 4
Output: 4
Explanation:
sumOdd = 1 + 3 + 5 + 7 = 16sumEven = 2 + 4 + 6 + 8 = 20Hence, GCD(sumOdd, sumEven) = GCD(16, 20) = 4.
Example 2:
Input: n = 5
Output: 5
Explanation:
sumOdd = 1 + 3 + 5 + 7 + 9 = 25sumEven = 2 + 4 + 6 + 8 + 10 = 30Hence, GCD(sumOdd, sumEven) = GCD(25, 30) = 5.
Constraints:
1 <= n <= 1000When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Add the first n positive odd numbers and the first n positive even numbers one at a time, then take the greatest common divisor of those two totals.
Here's how the algorithm would work step-by-step:
import math
def gcd_of_odd_and_even_sums(n):
odd_sum = 0
even_sum = 0
for index in range(n):
odd_sum += 2 * index + 1
even_sum += 2 * (index + 1)
return math.gcd(odd_sum, even_sum)
The sum of the first n positive odd numbers is n squared, and the sum of the first n positive even numbers is n times (n + 1). Those two values are always multiples of n and share no larger common factor, so their greatest common divisor is n.
Here's how the algorithm would work step-by-step:
def gcd_of_odd_and_even_sums(n):
return n
| Case | How to Handle |
|---|---|
| n is 1 | The odd sum is 1 and the even sum is 2, so the greatest common divisor is 1, which equals n. |
| n is 4 | The odd sum is 16 and the even sum is 20, so the greatest common divisor is 4, matching the example. |
| n is at the top of the allowed range | Building both sums by addition can overflow a 32-bit integer. The closed form returns n directly. |