Algorithms | Misc | Question 15

What is the return value of following function for 484? What does it to in general?

filter_none

edit
close

play_arrow

link
brightness_4
code

bool fun(int n)
{
    int sum = 0;
    for (int odd = 1; n > sum; odd = odd+2)
       sum = sum + odd;
    return (n == sum);
}

chevron_right


(A) False, it checks whether a given number is power of 3
(B) False, it checks whether a given number is even or not
(C) False, it checks whether a given number is odd or not
(D) True, it checks whether a given number is perfect square.


Answer: (D)

Explanation: The given function adds all odd numbers 1, 3, 5, 7, 9, 11…. till the sum is smaller than n. If the sum becomes equal to n, then it returns true. This is basically a test for perfect square numbers.

All perfect square numbers can be written as sum of odd numbers.

4 = 1 + 3
9 = 1 + 3 + 5
16 = 1 + 3 + 5 + 7
36 = 1 + 3 + 5 + 7 + 9
49 = 1 + 3 + 5 + 7 + 9 + 11

Quiz of this Question

My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.