Question

I'm attempting to calculate a modulus using 2 BigIntegers in C#.

Here's the method in question:

    static List<int> Get(BigInteger possibleColours, BigInteger length, BigInteger i)
    {
        List<int> ret = new List<int>();
        BigInteger sizes = 1;


        for (int j = 0; j < length; j++)
        {
            BigInteger index = (i/sizes) % possibleColours;

            ret.Add((int)index);
            sizes *= possibleColours;
        }
        return ret;
    }

This line is where the problem is:

BigInteger index = (i/sizes) % possibleColours;

The divide operation seems to work fine, but the modulus always seems to set index to 0, no matter which way I break it up, i.e. to do one operation per line.

Any help would be appreciated!

Was it helpful?

Solution

Following data samples you provide:

possibleColours: 65536,  
i: 20

You increment sizes here:

sizes *= possibleColours;

so already on second iteration you have (applying sample data provided in place):

                    i   sizes   possibleColours
BigInteger index = (20/65536) % 65536;

where 20/65536 == 0 as you devide integers, so result of devision is also integer itself.

After we get:

BigInteger index = 0 % 65536;, so index==0.

That means after first iteration you will get always 0, what your are experiencing actually.

OTHER TIPS

Both i and sizes are BigInteger. So whenever sizes>i, (i/sizes)==0 because it's an integer division. That could be the problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top