Esempio n. 1
0
        public static BigInt mod(BigInt a, BigInt b)
        {
            if (!greater(b, new BigInt("0")))
            {
                throw new ArgumentException("b must be >0");
            }
            int[]  res      = new int[a.number.Length];
            BigInt curValue = new BigInt("0");

            for (int i = a.number.Length - 1; i >= 0; i--)
            {
                curValue.LevelUp();
                curValue.number[0] = a.number[i];
                // подбираем максимальное число x, такое что b * x <= curValue
                int x = 0;
                int le = 0, r = BASE;
                while (le <= r)
                {
                    int    m   = (le + r) >> 1;
                    BigInt cur = multiply(b, valueOf(m));
                    if (lessEqualAbs(cur, curValue))
                    {
                        x  = m;
                        le = m + 1;
                    }
                    else
                    {
                        r = m - 1;
                    }
                }
                res[i] = x;

                curValue = subtract(curValue, multiply(b, valueOf(x)));
            }
            if (less(a, BigInt.ZERO) && !equal(curValue, ZERO))
            {
                return(subtract(b, curValue));
            }
            else
            {
                return(curValue);
            }
        }
Esempio n. 2
0
        public static BigInt divide(BigInt a, BigInt b)
        {
            if (b.isZero())
            {
                throw new ArgumentException("divide to zero");
            }
            int[]  res      = new int[a.number.Length];
            BigInt curValue = new BigInt("0");

            for (int i = a.number.Length - 1; i >= 0; i--)
            {
                curValue.LevelUp();
                curValue.number[0] = a.number[i];
                int x = 0;
                int le = 0, r = BASE;
                while (le <= r)
                {
                    int    m   = (le + r) >> 1;
                    BigInt cur = multiply(b, valueOf(m));
                    if (lessEqualAbs(cur, curValue))
                    {
                        x  = m;
                        le = m + 1;
                    }
                    else
                    {
                        r = m - 1;
                    }
                }
                res[i]   = x;
                curValue = subtract(curValue, multiply(b, valueOf(x)));
            }
            if (less(a, BigInt.ZERO) && !equal(curValue, ZERO))
            {
                return(subtract(new BigInt(deleteLeadingZerosOfArray(res), a.Negative == b.Negative ? false : true), valueOf(1)));
            }
            return(new BigInt(deleteLeadingZerosOfArray(res), a.Negative == b.Negative ? false : true));
        }