Question: The following C language code aimed to compute 1+2+3 . . . +n using divide and conquer approach, where n is an integer number. But

The following C language code aimed to compute 1+2+3 . . .The following C language code aimed to compute 1+2+3 . . . +n using divide and conquer approach, where n is an integer number. But the code provides correct answer when n is 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, . . .. Correct the code (i.e., the sum function) so that it provides correct answer when n is 1, 2, 3, 4, 5, 6, 7, 8, 9, . . ..

1. (14 marks) The following language code aimed to compute 1+2+3 ... tn using divide and conquer approach, where n is an integer number. But the code provides correct answer when n is 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, .... Correct the code (i.e., the sum function so that it provides correct answer when n is 1, 2, 3, 4, 5, 6, 7, 8, 9, .... #include int sum(int n) if (n==1) return 1; if (n>1) return 2*sum (n/2)+(n/2)*(n/2); int main() int n; printf( "Enter the value of n: "); scanf("%d", &n); int res=sum(n); printf ("Output: %d", res)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!