Open In App

Algorithms | Misc | Question 15

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




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

(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

Article Tags :