DEV Community

Discussion on: Daily Challenge #134 - Rice and Chessboard Problem

Collapse
 
andreasjakof profile image
Andreas Jakof • Edited

inspired by Diego Hdez' Python solution, but with a for-loop instead of a recursion and in C#

public static int Squaresneeded(ulong grains)
{
    int tile = 0;
    for(;grains > 0;++tile)
        grains = grains >> 1;

    return tile;
}

My original solution shifted the other way round building a potential and comparing that with the number of grains.

public static int Squaresneeded(ulong grains)
{
    int tile = 1;
    ulong potential = 1;
    for (;potential < grains;++tile)
    {
        potential = (potential << 1) + 1;
    }
    return tile;
}