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

| 我遇到了来自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;
    }

}
    
已邀请:
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;
}
    
Int64.MaxValue是9,223,372,036,854,775,807,即19个字符。因此,您实在无法满足要求。我建议您查看有关处理大数的问题。     
尝试使用此功能代替\“ 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;
    }
(由于您所有的数字都是正数,因此像原始的MathMod函数中那样使用Math.Abs​​没有意义)。 使用这种方式:
modulo = ModString(mergedNumber,97);
自1.1版以来,此版本应可用于所有版本的.NET,而无需BigInteger。     
您正在寻找的答案将在此处显示。它包括多种方式来计算巨大数的模数。对于国际银行帐号,我使用了与此处所述类似的方法。 此处是指向具有复制粘贴方法的人员的直接链接。     

要回复问题请先登录注册