Ramanujan Nested Radicals – Solution

The topic for this month’s Exercise is to code a recursive function that solves the Ramanujan Nested Radical, illustrated in Figure 1. Remember that Ramanujan created and solved this puzzle in his head. #genius

Figure 1. One of Ramanujan’s more famous nested radicals also called an infinite identity.

In past Exercises on this blog, I’ve looked at continued fractions and nested radicals such as this one and recursion immediately comes to mind as a way to code it. Of course, the issue with recursion is how to unwind the thing.

For my solution, the root() function includes an integer argument count. This variable decrements each time the function calls itself until the value of count is zero. At this point, the recursion unwinds.

2026_08-Exercise.c

#include <stdio.h>
#include <math.h>

float root(float a,int count)
{
    while( count-- )
        return( sqrt(1.0+(a+1.0) * root(a+1.0,count)) );
    return(a);
}

int main()
{
    float a = 0.0;

    a = root(1.0,25);
    printf("%f\n",a);

    return 0;
}

In the main() function, the recursive root() function is initially called with values of one and 25. The one is written as 1.0, which the compiler identifies as a real number; 25 is an integer. I found that 25 repetitions is adequate to reach the result of 3.0 (at least on my computers).

My C language version of the Ramanujan Nested Radical thingy appears in the return statement in the root() function:

sqrt(1.0+(a+1.0) * root(a+1.0,count))

Variable a represents the incrementing value in the nested radical, increasing by one each time the root() function is called. The result is finally returned once the value of count is zero, which happens in the while statement: while( count-- )

Remember to add the -lm switch when building this code in Linux at the terminal prompt. This switch brings in the math library, which is required for the sqrt() function to behave.

Here is output from a sample run:

3.000000

I hope your solution met with success!

3 thoughts on “Ramanujan Nested Radicals – Solution

  1. I edited your solution to use 32 iterations the same as mine and to print the result after each iteration. The values are different although they both end with 3.000000. Completely baffled!

    33.015148
    32.518990
    31.766156
    30.886642
    29.945160
    28.973513
    27.987226
    26.993849
    25.997043
    24.998580
    23.999319
    22.999674
    21.999844
    20.999926
    19.999965
    18.999983
    17.999992
    16.999996
    15.999998
    14.999999
    14.000000
    13.000000
    12.000000
    11.000000
    10.000000
    9.000000
    8.000000
    7.000000
    6.000000
    5.000000
    4.000000
    3.000000

Leave a Reply