BUPT-homework/semester1/pset3/3-sum.c

32 lines
663 B
C
Raw Permalink Normal View History

2021-10-12 20:24:51 +08:00
// Try to use recursion to solve this problem.
2021-10-12 13:18:54 +08:00
#include <stdio.h>
2021-10-12 20:24:51 +08:00
// function prototypes.
unsigned long long int sum(unsigned long long int n);
2021-10-12 13:18:54 +08:00
int main(void) {
2021-10-12 20:24:51 +08:00
// Initialize variables and get input from user.
unsigned long long int num;
scanf("%lld", &num);
2021-10-12 13:18:54 +08:00
2021-10-12 20:24:51 +08:00
// Calculate the sum of the numbers. (Can be optimized.)
unsigned long long int num1 = 0;
for (int i = 1; i <= num; i++) {
num1 += sum(i);
}
2021-10-12 13:18:54 +08:00
2021-10-12 20:24:51 +08:00
printf("%lld\n", num1);
2021-10-12 13:18:54 +08:00
return 0;
}
2021-10-12 20:24:51 +08:00
unsigned long long int sum(unsigned long long int n) {
if (n == 1 || n == 2) { // Case 1: n is 1 or 2
return 0;
} else { // Case 2: n is not
return n * (n - 1) * (n - 2) + sum(n - 1);
}
}