add problem 3

This commit is contained in:
juan 2021-10-12 13:18:54 +08:00
parent 938c6a265a
commit 2af0e53a15
No known key found for this signature in database
GPG key ID: 5C1E5093C74F1DC7
2 changed files with 51 additions and 0 deletions

27
pset3/3-sum-problem.c Normal file
View file

@ -0,0 +1,27 @@
// 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);
// Print values
printf("%lld\n", sum(num));
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);
}
}

24
pset3/3-sum.c Normal file
View file

@ -0,0 +1,24 @@
#include <stdio.h>
int main(void) {
// Initialize variables and get input
long long sum = 0;
long long n;
scanf("%lld", &n);
// if n is smaller than 3
if (n < 3) {
printf("0");
return 0;
}
// Iterate through all
for (long long i = 3; i < n; i++) {
sum += i * (i - 1) * (i - 2);
}
// Print the result
printf("%lld\n", sum);
return 0;
}