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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With