Java用快速幂还是爆内存,求救!给关!
查看原帖
Java用快速幂还是爆内存,求救!给关!
1406815
xiaobu321楼主2024/11/12 17:28

Java内存爆了,感觉代码没什么问题啊?始终70分 爆了内存,快速幂也用了,这咋办啊?求救!!!!!

import java.math.BigInteger;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long p = scanner.nextLong();

        BigInteger bigInteger = new BigInteger("2");
        bigInteger=bigInteger.pow((int) p);
        bigInteger=bigInteger.add(new BigInteger("-1"));


        //进行格式化输出
        char[] value = bigInteger.toString().toCharArray();
        int length = value.length;
        System.out.println(length);
        if (length>=500){
            int k=length-500;
            for (int i = 1; i <= 10; i++) {
                for (int j = 1; j <= 50; j++) {
                    System.out.print(value[k++]);
                }
                System.out.println();
            }
        }else {
            int k=0,count=0;
            for (int i = 1; i <= 10; i++) {
                for (int j = 1; j <= 50; j++) {
                    if (count+length>=500){
                        System.out.print(value[k++]);
                    }else {
                        System.out.print("0");
                    }
                    count++;
                }
                System.out.println();
            }
        }


    }

//    /**
//     * x的a的次方 快速幂
//     * @param a
//     * @param n
//     * @return 返回结果
//     */
//    public static BigInteger pow(BigInteger a, long n){
//        BigInteger r=new BigInteger("1");
//        while (n!=0){
//            if (n%2==1)
//                r=r.multiply(a);
//            a=a.multiply(a);
//            n= (long) Math.floor(n/2);
//        }
//        return r;
//    }
//

}
2024/11/12 17:28
加载中...