来自非常大的int C#的模数

时间:2011-04-14 11:22:22

标签: c# c#-4.0 modulo

我遇到了来自int的modulo有31个字符的问题。它似乎在错误上 Int64 convertedNumber = Int64.Parse(mergedNumber); Value was either too large or too small for an Int64. (Overflow Exception) class GeneratorRachunkow { private static string numerRozliczeniowyBanku = "11111155"; // 8 chars private static string identyfikatorNumeruRachunku = "7244"; // 4 chars private static string stalaBanku = "562100"; // 6 chars public static string generator(string pesel, string varKlientID) { string peselSubstring = pesel.Substring(pesel.Length - 5); // 5 chars (from the end of the string); string toAttach = varKlientID + peselSubstring; string indywidualnyNumerRachunku = string.Format("{0}", toAttach.ToString().PadLeft(13, '0')); // merging pesel with klient id and adding 0 to the begining to match 13 chars string mergedNumber = numerRozliczeniowyBanku + identyfikatorNumeruRachunku + indywidualnyNumerRachunku + stalaBanku; // merging everything -> 31 chars Int64 convertedNumber = Int64.Parse(mergedNumber); Int64 modulo = MathMod(convertedNumber, 97); Int64 wynik = 98 - modulo; string wynikString = string.Format("{0}", wynik.ToString().PadLeft(2, '0')); // must be 2 chars indywidualnyNumerRachunku = wynikString + numerRozliczeniowyBanku + identyfikatorNumeruRachunku + indywidualnyNumerRachunku; return indywidualnyNumerRachunku; } private static Int64 MathMod(Int64 a, Int64 b) { return (Math.Abs(a * b) + a) % b; } } 。如何修复它以便modulo不会出错?

{{1}}

4 个答案:

答案 0 :(得分:5)

Int64的最大值为9223372036854775807(打印时为19个字符)。您可能希望使用BigInteger(在.NET 4中引入):

public static string generator(string pesel, string varKlientID) { 
    // I have cut some code here to keep it short
    BigInteger convertedNumber;
    if (BigInteger.TryParse(mergedNumber , out convertedNumber))
    {
        BigInteger modulo = convertedNumber % 97;           
        // The rest of the method goes here...
    }
    else
    {
        // string could not be parsed to BigInteger; handle gracefully
    }

}

private static BigInteger MathMod(BigInteger a, BigInteger b)
{
    return (BigInteger.Abs(a * b) + a) % b;
}

答案 1 :(得分:2)

Int64.MaxValue是9,223,372,036,854,775,807,共19个字符。所以你不能适应它。我建议看this question处理大数字。

答案 2 :(得分:2)

尝试此功能而不是“MathMod”:

    static int ModString(string x, int y)
    {
        if (x.Length == 0)
            return 0;
        string x2 = x.Substring(0,x.Length - 1); // first digits
        int x3 = int.Parse(x.Substring(x.Length - 1));   // last digit
        return (ModString(x2, y) * 10 + x3) % y;
    }

(因为你的所有数字都是正数,所以使用Math.Abs​​是没有意义的,就像你原来的MathMod函数一样)。

以这种方式使用:

modulo = ModString(mergedNumber,97);

这应该适用于1.1以后的所有.NET版本,而不需要BigInteger。

答案 3 :(得分:1)

您正在寻找的答案已经展示here。它包括各种方式来计算大数的模数。我使用了此处描述的类似方法来处理国际银行帐号。

指向具有可复制可用方法的人的直接链接是here

相关问题