#3658

GCD of Odd and Even Sums

Easy
MathNumber TheoryMathematical InductionNumber Theory
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(log(min(sumOdd, sumEven)))
Space
O(1)
O(1)
💡

Intuition

Time O(log(min(sumOdd, sumEven)))Space O(1)

Use the mathematical formulas for the sums of odd and even numbers, which are n² and n(n + 1) respectively. This avoids unnecessary loops.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate sumOdd as n * n.
  2. 2Step 2: Calculate sumEven as n * (n + 1).
  3. 3Step 3: Return GCD of sumOdd and sumEven.
solution.py6 lines
1import math
2
3def gcd_of_sums(n):
4    sumOdd = n * n
5    sumEven = n * (n + 1)
6    return math.gcd(sumOdd, sumEven)

Complexity note: The GCD calculation is efficient, leading to a logarithmic time complexity based on the values of sumOdd and sumEven. Space complexity remains O(1).

  • 1The sum of the first n odd numbers is n².
  • 2The sum of the first n even numbers is n(n + 1).

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.