nayuki / Project-Euler-solutions

Runnable code for solving Project Euler problems in Java, Python, Mathematica, Haskell.
https://www.nayuki.io/page/project-euler-solutions
1.89k stars 675 forks source link

How are you calculating floor of a number #16

Closed AbhimanyuAryan closed 5 years ago

AbhimanyuAryan commented 5 years ago

I saw you calculating sqrt of some number but I didn't get how you are calculating floor of that number in this code

def sqrt(x):
    assert x >= 0
    i = 1
    while i * i <= x:
        i *= 2
    y = 0
    while i > 0:
        if (y + i)**2 <= x:
            y += i
        i //= 2
    return y
nayuki commented 5 years ago

This is an integer square root algorithm. For a given integer x, this function finds the largest integer y such that y * y <= x. Hence, y = floor(sqrt(x)).

Try adding some print statements to see the intermediate values of i and y, and try calling the function different values of x.

If you have further questions, please make a post on Stack Overflow and the fine volunteers will answer you: https://stackoverflow.com/questions/ask