aboutsummaryrefslogtreecommitdiff
path: root/3_consec_int_sum.c
blob: 8cc4d40211201333eb9f7209a0536017f20beda5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 2177. Find Three Consecutive Integers That Sum to a Given Number
#include <stdio.h>
#include <stdlib.h>

/*
 * given an integer 'num', return 3 consecutive integers (as a sorted array)
 * that sum to 'num'. if 'num' cannot be expressed as the sum of 3 consecutive
 * integers, return an empty array.
 */

long long *sumOfThree(long long num, int *returnSize) {
  if ((num - 3) % 3 != 0) {
    *returnSize = 0;
    return NULL;
  }
  *returnSize = 3;
  long long *ans = malloc(3 * sizeof(long long));
  ans[0] = (num - 3) / 3;
  ans[1] = ans[0] + 1;
  ans[2] = ans[1] + 1;
  return ans;
}

int main() {
  long long num1 = 33, num2 = 4;
  int rs1[] = {}, rs2[] = {};
  printf("%p\n", sumOfThree(num1, rs1)); // expect: 10, 11, 12
  printf("%p\n", sumOfThree(num2, rs2)); // expect: nil
}