DEV Community

Damien Sedgwick
Damien Sedgwick

Posted on • Updated on

ChatGPT - Complex Coding Challenges: 7 KYU

Hello there!

Today we are back with the second article of this series in which we put ChatGPT to the test and without me waffling on any further, lets take a look at the challenge.

Here is the challenge Sum of odd numbers

Followed by the instructions and examples:

Given the triangle of consecutive odd numbers:

             1
          3     5
       7     9    11
   13    15    17    19
21    23    25    27    29
...
Calculate the sum of the numbers in the nth row of this triangle (starting at index 1) e.g.: (Input --> Output)

1 -->  1
2 --> 3 + 5 = 8
Enter fullscreen mode Exit fullscreen mode

Not a great deal to go off of, but simple enough that ChatGPT should not struggle... I think.

Solving it in JavaScript

function rowSumOddNumbers(n) {
     // Calculate the starting number for the nth row
  let start = (n * (n - 1)) + 1;

  // Calculate the sum of the numbers in the nth row
  let sum = 0;

  for (let i = 0; i < n; i++) {
    sum += start + (2 * i);
  }

  return sum;
}
Enter fullscreen mode Exit fullscreen mode

Running the above code makes all tests pass!

Solving it in C

#include <inttypes.h>

uint64_t rowSumOddNumbers(uint32_t n) {
    uint64_t start_num = 1, sum = 0;

    // Calculate the starting number of the nth row
    for (uint32_t i = 1; i < n; i++) {
        start_num += 2 * i;
    }

    // Calculate the sum of the numbers in the nth row
    for (uint32_t i = 0; i < n; i++) {
        sum += start_num + 2 * i;
    }

    return sum;
}
Enter fullscreen mode Exit fullscreen mode

It took 2 attempts for the C implementation to be correct however I think the issue was not starting a new prompt with ChatGPT

Solving it in SQL

SELECT SUM(nums.num) as sum_of_row
FROM 
  (SELECT ((n-1)*(n-1)+1) as num 
   FROM nums WHERE n = [input row number]) as nums
UNION ALL
SELECT SUM(nums.num) as sum_of_row
FROM 
  (SELECT ((n-1)*(n-1)+1) as num 
   FROM nums WHERE n = [input row number]) as nums
  JOIN 
  (SELECT ((n-1)*(n-1)+1) as num 
   FROM nums WHERE n = [input row number]-1) as nums_prev
  ON nums_prev.num < nums.num AND nums_prev.num % 2 = 1
Enter fullscreen mode Exit fullscreen mode

After many attempts, I could not get ChatGPT to understand what it needed to do in order to pass this challenge.

Even before testing the SQL solution I have a feeling it is wrong because it is writing very verbose solutions to what I feel should be quite trivial at this point.

Maybe we will continue with SQL, maybe not. It depends on whether or not I figure out this current challenge!

Top comments (0)