简体   繁体   中英

Exception in thread "main" java.lang.ArithmeticException: BigInteger would overflow supported range

code image

import java.math.BigInteger;

public class GaayuProbOne {
    static void power(int N, int P) {
        BigInteger result = new BigInteger("10");
        BigInteger res = result.pow(P);
        System.out.println(res);
    }

    static double power1(int N, int P) {
        double res =Math.pow(N,P);
        return res;
    }

    public static void main(String[] args) {
        int N = 10;
        double P = 25*power1(10,25);
        System.out.println(P);
        int q = (int) P;
        power(N, q);
    }
}

This code is to calculate 10 25 10 25 program in java.
How to calculate it?

Exception in thread "main" java. lang. Arithmetic Exception: Big Integer would overflow supported range

Is there any method to calculate 10 25 10 25 in a java program?

Note: the question has changed significantly since this answer was posted. It originally asked for a way of computing 10^25 x 10^25.

The code has multiple problems:

  • It uses unconventional variable names - not a bug, but still something to fix
  • The power method ignores the value of N
  • You're performing floating point arithmetic for no obvious reason (using Math.pow )
  • You're multiplying by 25, which occurs nowhere in what you're trying to achieve
  • You're casting a very, very large number (25 * 10^25) to int , when the maximum value of int is just 2147483647
  • You're trying to compute 10^2147483647 in the last line - without the previous problem, you'd be trying to compute 10^(25*10^25), which definitely isn't what is specified

The actual code you need is significantly simpler:

  • Find 10^25, as a BigInteger
  • Multiply that by itself

Simple code to do that:

import java.math.BigInteger;

public class Test {
    public static void main(String[] args) {
        int n = 10;
        int p = 25;

        BigInteger tmp = BigInteger.valueOf(n).pow(p);
        BigInteger result = tmp.multiply(tmp);
        System.out.println(result);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM