Facebook Pixel

3658. GCD of Odd and Even Sums

Problem Description

You are given an integer n. Your task is to find the GCD (greatest common divisor) of two specific sums:

  1. sumOdd: The sum of the first n odd numbers

    • For example, if n = 3, the first 3 odd numbers are 1, 3, 5, so sumOdd = 1 + 3 + 5 = 9
  2. sumEven: The sum of the first n even numbers

    • For example, if n = 3, the first 3 even numbers are 2, 4, 6, so sumEven = 2 + 4 + 6 = 12

Your goal is to calculate these two sums and then return their GCD.

The key insight here is recognizing the mathematical formulas for these sums:

  • The sum of the first n odd numbers equals
  • The sum of the first n even numbers equals n(n + 1)

Once we have these values, we need to find their GCD. Since n and n + 1 are consecutive integers (and therefore coprime - their GCD is 1), the GCD of and n(n + 1) simplifies to n.

This explains why the solution simply returns n - it's the mathematical result of finding GCD(n², n(n + 1)).

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

Let's first figure out what these sums actually are. If we write out a few examples:

  • First 3 odd numbers: 1, 3, 5 → sum = 9 = 3²
  • First 4 odd numbers: 1, 3, 5, 7 → sum = 16 = 4²
  • First 3 even numbers: 2, 4, 6 → sum = 12 = 3 × 4
  • First 4 even numbers: 2, 4, 6, 8 → sum = 20 = 4 × 5

We can observe a pattern: the sum of the first n odd numbers is always , and the sum of the first n even numbers is always n × (n + 1).

Now we need to find GCD(, n × (n + 1)).

Let's think about what divides both numbers. Any common divisor of and n × (n + 1) must divide . Since n × (n + 1) = n × n + n, any common divisor must also divide this expression.

Here's the key insight: n clearly divides both and n × (n + 1). But can anything larger than n divide both?

If we factor out n from both expressions:

  • = n × n
  • n × (n + 1) = n × (n + 1)

So we're really asking: what's the GCD of n and (n + 1)? Since these are consecutive integers, they share no common factors except 1. This means n and n + 1 are coprime.

Therefore, the GCD of and n × (n + 1) is exactly n - nothing larger can divide both, and n definitely does divide both.

Solution Approach

The implementation is remarkably elegant once we understand the mathematical relationship.

Based on our mathematical analysis:

  • Sum of first n odd numbers =
  • Sum of first n even numbers = n(n + 1)

To find the GCD of these two values, we leverage the fact that:

  1. n is a common factor of both and n(n + 1)
  2. After factoring out n, we're left with n and (n + 1)
  3. Since n and n + 1 are consecutive integers, they are coprime (their GCD is 1)

Therefore, GCD(, n(n + 1)) = n × GCD(n, n + 1) = n × 1 = n

The solution simply returns n directly:

class Solution:
    def gcdOfOddEvenSums(self, n: int) -> int:
        return n

This is a constant time O(1) solution with O(1) space complexity. We don't need to:

  • Calculate the actual sums
  • Implement a GCD algorithm (like Euclidean algorithm)
  • Use any loops or recursion

The mathematical proof guarantees that for any positive integer n, the answer is always n itself, making this one of the most efficient solutions possible.

Ready to land your dream job?

Unlock your dream job with a 3-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through a concrete example with n = 4 to illustrate the solution approach.

Step 1: Identify the first n odd and even numbers

  • First 4 odd numbers: 1, 3, 5, 7
  • First 4 even numbers: 2, 4, 6, 8

Step 2: Calculate the sums

  • sumOdd = 1 + 3 + 5 + 7 = 16
  • sumEven = 2 + 4 + 6 + 8 = 20

Step 3: Verify the mathematical formulas

  • sumOdd = 16 = 4² ✓
  • sumEven = 20 = 4 × (4 + 1) = 4 × 5 ✓

Step 4: Find GCD(16, 20) using the mathematical insight

Instead of using the Euclidean algorithm, we apply our mathematical understanding:

  • 16 = 4² = 4 × 4
  • 20 = 4 × 5

We can factor out 4 from both numbers:

  • GCD(16, 20) = GCD(4 × 4, 4 × 5) = 4 × GCD(4, 5)

Since 4 and 5 are consecutive integers, they share no common factors except 1:

  • GCD(4, 5) = 1

Therefore:

  • GCD(16, 20) = 4 × 1 = 4

Step 5: Verify the result The answer is 4, which equals our input n. This confirms that for n = 4, the GCD of the sum of the first 4 odd numbers and the sum of the first 4 even numbers is indeed 4.

This example demonstrates why the solution simply returns n - the mathematical relationship guarantees this result for any positive integer input.

Solution Implementation

1class Solution:
2    def gcdOfOddEvenSums(self, n: int) -> int:
3        """
4        Calculate the GCD of the sum of odd numbers and sum of even numbers from 1 to n.
5      
6        Args:
7            n: Upper bound for the range of numbers to consider
8          
9        Returns:
10            The greatest common divisor of odd_sum and even_sum
11        """
12        # Calculate sum of odd numbers from 1 to n
13        odd_sum = 0
14        for i in range(1, n + 1, 2):  # Start at 1, increment by 2
15            odd_sum += i
16          
17        # Calculate sum of even numbers from 2 to n  
18        even_sum = 0
19        for i in range(2, n + 1, 2):  # Start at 2, increment by 2
20            even_sum += i
21          
22        # Handle edge case where one sum might be 0
23        if odd_sum == 0:
24            return even_sum
25        if even_sum == 0:
26            return odd_sum
27          
28        # Calculate GCD using Euclidean algorithm
29        def gcd(a: int, b: int) -> int:
30            """Helper function to calculate GCD using Euclidean algorithm"""
31            while b:
32                a, b = b, a % b
33            return a
34          
35        return gcd(odd_sum, even_sum)
36
1class Solution {
2    /**
3     * Calculates the greatest common divisor (GCD) of the sum of odd numbers 
4     * and the sum of even numbers from 1 to n.
5     * 
6     * Mathematical insight:
7     * Through mathematical derivation, the GCD of these two sums
8     * can be simplified to a direct function of n.
9     * 
10     * @param n The upper bound of the range (inclusive)
11     * @return The GCD of the sum of odd numbers and sum of even numbers
12     */
13    public int gcdOfOddEvenSums(int n) {
14        // The mathematical formula simplifies to returning n directly
15        // This works because of the specific relationship between
16        // the sum formulas for consecutive odd and even numbers
17        return n;
18    }
19}
20
1class Solution {
2public:
3    /**
4     * Calculates the GCD of the sum of odd numbers and sum of even numbers
5     * from 1 to n.
6     * 
7     * @param n The upper limit of the range [1, n]
8     * @return The GCD of odd sum and even sum
9     */
10    int gcdOfOddEvenSums(int n) {
11        // Direct mathematical result: returns n as the GCD
12        // This appears to be a simplified/optimized solution
13        // based on mathematical properties of the sums
14        return n;
15    }
16};
17
1/**
2 * Calculates the greatest common divisor (GCD) of the sum of numbers at odd positions
3 * and the sum of numbers at even positions from 1 to n.
4 * 
5 * Mathematical insight: For consecutive integers from 1 to n:
6 * - Sum of odd positions (1, 3, 5, ...) and sum of even positions (2, 4, 6, ...)
7 * - The GCD of these two sums always equals n
8 * 
9 * @param n - The upper limit of the range [1, n]
10 * @returns The GCD of odd-positioned sum and even-positioned sum
11 */
12function gcdOfOddEvenSums(n: number): number {
13    // Direct formula: The GCD pattern simplifies to n itself
14    return n;
15}
16

Time and Space Complexity

The time complexity is O(1) because the function performs a single operation - returning the input value n. This operation takes constant time regardless of the size of the input.

The space complexity is O(1) because the function does not allocate any additional memory that scales with the input. It simply returns the input parameter without creating any auxiliary data structures or variables.

Common Pitfalls

1. Misunderstanding the Problem Statement

The code calculates the sum of ALL odd and even numbers from 1 to n, but the problem asks for the sum of the FIRST n odd numbers and FIRST n even numbers.

Incorrect interpretation:

  • Sum of odd numbers from 1 to n: If n=6, sums 1+3+5 = 9
  • Sum of even numbers from 2 to n: If n=6, sums 2+4+6 = 12

Correct interpretation:

  • First n odd numbers: If n=3, sums 1+3+5 = 9 (first 3 odd numbers)
  • First n even numbers: If n=3, sums 2+4+6 = 12 (first 3 even numbers)

Solution:

def gcdOfOddEvenSums(self, n: int) -> int:
    # Calculate sum of first n odd numbers
    odd_sum = 0
    odd_num = 1
    for i in range(n):
        odd_sum += odd_num
        odd_num += 2
  
    # Calculate sum of first n even numbers
    even_sum = 0
    even_num = 2
    for i in range(n):
        even_sum += even_num
        even_num += 2
  
    # Calculate GCD
    def gcd(a, b):
        while b:
            a, b = b, a % b
        return a
  
    return gcd(odd_sum, even_sum)

2. Over-Engineering the Solution

Given the mathematical insight that the answer is always n, implementing loops and GCD algorithms is unnecessary complexity.

Optimal solution:

def gcdOfOddEvenSums(self, n: int) -> int:
    return n

3. Not Leveraging Mathematical Formulas

Even if you want to show the calculation explicitly, using loops is inefficient when direct formulas exist:

  • Sum of first n odd numbers = n²
  • Sum of first n even numbers = n(n+1)

Better approach with formulas:

def gcdOfOddEvenSums(self, n: int) -> int:
    odd_sum = n * n  # n²
    even_sum = n * (n + 1)  # n(n+1)
  
    def gcd(a, b):
        while b:
            a, b = b, a % b
        return a
  
    return gcd(odd_sum, even_sum)  # Will always return n

4. Edge Case Handling Confusion

The edge case handling in the original code checks if sums are 0, but given n is a positive integer and we're summing positive numbers, neither sum can be 0. This adds unnecessary code that will never execute.

Discover Your Strengths and Weaknesses: Take Our 3-Minute Quiz to Tailor Your Study Plan:

In a binary min heap, the maximum element can be found in:


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More