Saturday 15 March 2014

c - What does this 'number' function do? -



c - What does this 'number' function do? -

i had question in exam - http://ideone.com/umausi

the code -

#include <stdio.h> int number(int n) { if(n == 1) homecoming n; int half = n/2; int k = 2*number(n/2) + half*half; homecoming (n%2)?(k+n):k; } int main(void) { printf("%d",number(11)); homecoming 0; }

i know to solve these type of questions, 1 should understand function doing. saves lot of time because don't have run each case(which can take longer time). instead ran case , found result. so, want know what 'number' function does? if meaningful calculating square or that. couldn't find generic reply it.

this recursive function calculate sum of n natural numbers 'n' input recursive function.

had tried sample inputs have deduced easily. below samples:-

input output

2 3

5 15

7 28

10 55

mathematical formula calculating sum of n natural numbers is:-

( n * ( n + 1 ) ) / 2

explanation ( molbdnilo ):-

suppose want sum numbers 1 100.

compute (1 + 100) + (2 + 99) + (3 + 98) + ... + (98 + 3) + (99 + 2) + (100 + 1) = 101 + 101 + ... + 101 = 100 * 101 = 10100.

since every number occurs twice in summation, sum you're looking

10100/2 = 5050;

the sum

n*(n+1)/2.

(if calculate 2*sum(n/2) number 'n', you'll notice (nn + 2n)/4, while sum(n) (2*nn + 2*n)/4). add together n*n/4 2*sum(n/2) , sum(n)).

edited in response comments:-

@halkujabra molbdnilo has given explanation.

@jonathan:- no integers include whole range of numbers on number line ( numbers without fractional part )

... -100, -50 , 0 , 50 ,100...

whole numbers non-negative integers i.e

0, 50, 100

natural numbers :- whole numbers - 0 , i.e

1, 50, 100

c function output

No comments:

Post a Comment