GCD of Odd and Even Sums Problem
#3658
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3658.
You are given an integer n. Your task is to compute the GCD (greatest common divisor) of two values:
sumOdd: the sum of the smallestnpositive odd numbers.sumEven: the sum of the smallestnpositive even numbers.
Return the GCD of sumOdd and sumEven.
Example 1:
Input: n = 4
Output: 4
Explanation:
- Sum of the first 4 odd numbers sumOdd = 1 + 3 + 5 + 7 = 16
- Sum of the first 4 even numbers sumEven = 2 + 4 + 6 + 8 = 20
Hence, GCD(sumOdd, sumEven) = GCD(16, 20) = 4.
Example 2:
Input: n = 5
Output: 5
Explanation:
- Sum of the first 5 odd numbers sumOdd = 1 + 3 + 5 + 7 + 9 = 25
- Sum of the first 5 even numbers sumEven = 2 + 4 + 6 + 8 + 10 = 30
Hence, GCD(sumOdd, sumEven) = GCD(25, 30) = 5.
Constraints:
1 <= n <= 1000
Solution
Approach: Mathematics
The first n odd numbers add up to n^2, and the first n even numbers add up to n(n + 1). Both are multiples of n, and n and n + 1 are coprime, so their greatest common divisor is exactly n.
Complexity: time O(1), space O(1).
class Solution:
def gcdOfOddEvenSums(self, n: int) -> int:
return n