[Solved] C# – Constantly adding 9 digits


Even after your edit, I don’t find the question very clear. However, I do think I understand that you are essentially trying to generate a random BigInteger value, and that you want the random value to be within a range defined by some specific number of digits.

For example, if you ask for a 10-digit value, some value between 0 and 9999999999 should be returned. If you ask for a 20-digit value, some value between 0 and 99999999999999999999 should be returned.

Based on that understanding, I believe this method should accomplish what you are asking:

BigInteger NextRandom(Random random, int digitCount)
{
    BigInteger result = 0;

    while (digitCount-- > 0)
    {
        result = result * 10 + random.Next(10);
    }

    return result;
}

Note that the number returned could have fewer than digitCount actual digits in it. In fact, there’s always a 1-in-10 chance of that happening. And a 1-in-100 chance of the result having fewer than (digitCount – 1) digits, etc.

If you want something different from that, please be more specific about the exact requirements of the output you want (read https://stackoverflow.com/help/how-to-ask for advice on how to present your question in a clear, answerable way).

For example, the above won’t generate a random value within some arbitrary range; the (exclusive) max value can only ever be a power of 10. Also, due to the way BigInteger works, if you are looking for a value with a specific number of binary digits, you can do that simply by using the Random.NextBytes() method, passing the resulting array (making modifications as appropriate to ensure e.g. positive values).

See also C# A random BigInt generator for more inspiration (I would’ve voted as that for a duplicate, but it seems from your description that you might be looking for a slightly different result than what’s requested in that question).

1

solved C# – Constantly adding 9 digits