From dbff279288ed6e3bff2e2d037f7e9a4c1a50975c Mon Sep 17 00:00:00 2001 From: juan Date: Tue, 12 Oct 2021 20:24:51 +0800 Subject: [PATCH] update 3 to the right solution --- pset3/3-sum-problem.c | 27 --------------------------- pset3/3-sum.c | 39 +++++++++++++++++++++++---------------- 2 files changed, 23 insertions(+), 43 deletions(-) delete mode 100644 pset3/3-sum-problem.c diff --git a/pset3/3-sum-problem.c b/pset3/3-sum-problem.c deleted file mode 100644 index 1d0ec6f..0000000 --- a/pset3/3-sum-problem.c +++ /dev/null @@ -1,27 +0,0 @@ -// Try to use recursion to solve this problem. -#include - -// 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); - } -} - diff --git a/pset3/3-sum.c b/pset3/3-sum.c index 8509a18..0d54938 100644 --- a/pset3/3-sum.c +++ b/pset3/3-sum.c @@ -1,24 +1,31 @@ +// Try to use recursion to solve this problem. #include +// function prototypes. + +unsigned long long int sum(unsigned long long int n); + 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\n"); - return 0; - } + // Initialize variables and get input from user. + unsigned long long int num; + scanf("%lld", &num); - // Iterate through all - for (long long i = 3; i <= n; i++) { - sum += i * (i - 1) * (i - 2); - } - - // Print the result - printf("%lld\n", sum); + // 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); + } +} +