Everything in Particular

February 4, 2009

C#: Doing a modulus (mod) operation on a very large number (> Int64.MaxValue)

Filed under: Development, Technology — omatase @ 5:54 pm
/// <summary>
/// calculates a modulus on any number, specifically
/// designed to work around the Int64 limits of the
/// current version of c# which cannot hold a number
/// larger than 9,223,372,036,854,775,807
/// </summary>
/// <param name="iban"></param>
/// <returns></returns>
private static int largeNumberModulus(string numberToModulus, int modulusOperand)
{
string modulusWorkingNumber = numberToModulus;

while (modulusWorkingNumber.Length > 0 && !(modulusWorkingNumber.Length < 18 && Int64.Parse(modulusWorkingNumber) < modulusOperand))
{
// number to work with
Int64 currentNumber = 0;
if (modulusWorkingNumber.Length > 18)
{
currentNumber = Int64.Parse(modulusWorkingNumber.Substring(0, 18));

// remove first 18 characters
modulusWorkingNumber = modulusWorkingNumber.Substring(18);
}
else
{
currentNumber = Int64.Parse(modulusWorkingNumber);

// remove remaining used characters
modulusWorkingNumber = string.Empty;
}

string carryOver = (currentNumber % modulusOperand).ToString();
modulusWorkingNumber = carryOver + modulusWorkingNumber;
}

return int.Parse(modulusWorkingNumber);
}

1 Comment »

  1. This is part of code I mage for my shop for IBAN validation. Feel free to use if some one need.

    static void Main(string[] args)
    {
    int modulo = 97;
    string input = Reverse(“100020778788920323232343433″);
    int result = 0;
    int lastRowValue = 1;

    for (int i = 0; i 0)
    {
    lastRowValue = ModuloByDigits(lastRowValue, modulo);
    }
    result += lastRowValue * int.Parse(input[i].ToString());
    }
    result = result % modulo;
    Console.WriteLine(string.Format(“Result: {0}”, result));
    }

    public static int ModuloByDigits(int previousValue, int modulo)
    {
    // Calculating the modulus of a large number Wikipedia http://en.wikipedia.org/wiki/International_Bank_Account_Number
    return ((previousValue * 10) % modulo);
    }
    public static string Reverse(string input)
    {
    char[] arr = input.ToCharArray();
    Array.Reverse(arr);
    return new string(arr);

    Comment by Jaroslav Kubacek — February 11, 2010 @ 11:59 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress