Java求救,给关注!爆内存了!

P1045 [NOIP2003 普及组] 麦森数

xiaobu321 @ 2024-11-12 17:37:55

Java求救,给关注!爆内存了!

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);
        int count=500;
        for (int i = 1; i <= 10*50; i++) {
            if (length-count>=0){
                System.out.print(value[length-count]);
            }else {
                System.out.print("0");
            }
            count--;
            if (i%50==0){
                System.out.println();
            }
        }
    }

}

by xiaobu321 @ 2024-11-12 17:38:38

我使用过快速幂了,这个就是快速幂,一样不行


by xiaobu321 @ 2024-11-12 17:40:01

70分爆了3个内存


by Hyxx @ 2024-11-19 23:31:00

可以写一个高精度乘法然后控制结果500位,或者用BigInteger的modPow来求一个2^P % 10^500


|