java余数怎么表达,如何使用Java计算极大指数的余数?

How do i calculate the remainder for extremely large exponential numbers using java ?

eg. (48^26)/2401

I tried using BIGINTEGER, however it gave the same output for large divisors.I'm not sure if BIG INTEGER can do this .I have tried all other PRIMITIVE data type.They seem to be insufficient.

FYI it tried the following code:

BigInteger a = new BigInteger("48");

a = a.pow(26);

BigInteger b = new BigInteger("2401");//49*49

a = a.mod(b);

System.out.println(a);

I don't know why i got the same output everytime, it's weird that it's working fine now.

The answer comes out to be 1128

解决方案

You can use repeated modulus of smaller numbers.

say you have

(a * b) % n

((A * n + AA) * (B * n + BB)) % n | AA = a %n & BB = b % n

(A * B * n^2 + A * N * BB + AA * B * n + AA * BB) % n

AA * BB % n since x * n % n == 0

(a % n) * (b % n) % n

In your case, you can write

48^26 % 2401

(48^2) ^ 13 % 2401

as

int n = 48;

for (int i = 1; i < 26; i++)

n = (n * 48) % 2401;

System.out.println(n);

int n2 = 48 * 48;

for (int i = 1; i < 13; i++)

n2 = (n2 * 48 * 48) % 2401;

System.out.println(n2);

System.out.println(BigInteger.valueOf(48).pow(26).mod(BigInteger.valueOf(2401)));

prints

1128

1128

1128

As @Ruchina points out, your example is small enough to calculate using a simple double expression.

for (int i = 1; i < 100; i++) {

BigInteger mod = BigInteger.valueOf(48).pow(i).mod(BigInteger.valueOf(2401));

double x = Math.pow(48, i) % 2401;

if (mod.intValue() != x) {

System.out.println(i + ": " + mod + " vs " + x);

break;

}

}

prints

34: 736 vs 839.0

In other words, any power of 48 is fine up to 33.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值