Intuition¶
The sum of the first n odd numbers is n^2, and the sum of the first n
even numbers is n(n + 1). So we need gcd(n^2, n(n + 1)). Since gcd(n, n + 1) = 1,
this simplifies to n.
Approach: Math¶
Return n directly — the GCD of n^2 and n(n + 1) is always n.
Approach: Euclidean GCD¶
- Compute
oddSum = n * nandevenSum = n * (n + 1). - Return
gcd(oddSum, evenSum)using the Euclidean algorithm.
Complexity¶
- Math: $$O(1)$$ time and space.
- Euclidean GCD: $$O(\log n)$$ time (Euclid on values up to $$n^2$$), $$O(1)$$ space.
Code¶
Go (Math)¶
Go (Euclidean GCD)¶
func gcdOfOddEvenSums(n int) int {
oddSum := n * n
evenSum := (n + 1) * n
return gcd(oddSum, evenSum)
}
func gcd(a, b int) int {
for b != 0 {
a, b = b, a%b
}
return a
}