Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling "Big" Integers in C#

How do I handle big integers in C#?

I have a function that will give me the product of divisors:

private static int GetDivisorProduct(int N, int product)
    {
        for (int i = 1; i < N; i++)
        {
            if (N % i == 0)
            {
                Console.WriteLine(i.ToString());
                product *= i;
            }
        }

        return product;
    }

The calling function is GetDivisorProduct(N, 1)

If the result is bigger than 4 digits , I should obtain only the last 4 digits. ( E.g. If I give an input of 957, the output is 7493 after trimming out only the last four values. The actual result is 876467493.).

Other sample inputs: If I give 10000, the output is 0.

The BigInteger class has been removed from the C# library!

How can I get the last four digits?

like image 506
priyanka.sarkar Avatar asked Jun 06 '09 15:06

priyanka.sarkar


People also ask

How do you deal with big numbers in C?

Usually, you would choose a base that is half the largest representable type so that there are no overflows. For instance, in modern C, you would choose uint32_t and do all the digit arithmetic in uint64_t . And don't forget: make the digit type unsigned so that there are no surprises.

What is big integer in C?

The BIGINT data type is a machine-independent method for representing numbers in the range of -2 63-1 to 2 63-1. ESQL/C provides routines that facilitate the conversion from the BIGINT data type to other data types in the C language. The BIGINT data type is internally represented with the ifx_int8_t structure.

How do you handle large numbers in C++?

In C++, we can use large numbers by using the boost library. This C++ boost library is widely used library. This is used for different sections.


1 Answers

If you're only looking at the last four digits, you don't need anything larger than an integer. Consider this:

When multiplying two numbers, if you are only interested in the least significant digits (i.e. the last four digits), then the upper-most digits will not have an effect on lowest digits of the outcome... so you can just "throw out" the most significant (right-side) digits before you multiply.

For example: I want to multiply two large numbers but I only need the last two digits:

int num1 = 123456789;
int num2 = 987654321;

int result = num1 * num2; // Last two digits would be "69" but this OVERFLOWS

but if we multiply only the last two digits...

int result = (num1 % 100) * (num2 % 100);  // result = 89 * 21

89 * 21 = 1869 (the last two digits are still "69" but we have not overflowed).

I used this technique to calculate the Six Right-Most Digits of 1,000,000 factorial.

like image 154
Joel James Avatar answered Sep 18 '22 17:09

Joel James