알고리즘 81 - Sum of odd numbers

tamagoyakii·2021년 12월 6일
0

알고리즘

목록 보기
81/89

Q.

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

A)

#include <inttypes.h>

uint64_t rowSumOddNumbers(uint32_t n) {
  uint64_t start = ((n - 1) * n ) + 1;
  uint64_t sum = 0;
  
  for (uint32_t i = 0; i < n; i++) {
    sum += start + (2 * i);
  }
  return sum;
}

이런 식으로 풀었는데, 암만해도 마지막 테스트 케이스가 통과를 못하더라.... 진짜 울고싶었다 😢
자료형 때문인걸로 추측이 되는데, 아직 이해가 되지는 않는다. 근데 진짜 열받는건 아래처럼 쓰면 통과가 된다는 것 ...! 😇

#include <inttypes.h>

uint64_t rowSumOddNumbers(uint32_t n) {
  return (n * n * n);
}

대체 왜 세제곱만 했는데 저 숫자가 나오는 것인지.. 도대체 누가 발견한 것인지...... 수포자인 나만 모르는 공식인건지.... 눈물이 앞을 가린다ㅎㅎ 간만에 c로 알고리즘 푸니까 적응이 안된다. 화이탱..

0개의 댓글