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

32 lines
663 B
C

// Try to use recursion to solve this problem.
#include <stdio.h>
// function prototypes.
unsigned long long int sum(unsigned long long int n);
int main(void) {
// Initialize variables and get input from user.
unsigned long long int num;
scanf("%lld", &num);
// 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);
}
printf("%lld\n", num1);
return 0;
}
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);
}
}