You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java BigInteger代码为何重复输出4次?结果正确但打印次数不符预期

问题排查:BigInteger乘法代码重复输出问题

你遇到的问题是代码执行后输出被重复打印多次,而非预期的1次。先来看你的代码:

import java.util.*;
import java.math.BigInteger;
class THIRTYSEVEN {
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        BigInteger a = new BigInteger("1");
        multiply(a,0,sc.nextInt());
    }
    static void multiply(BigInteger b, int loop, int power) {
        BigInteger result = b;
        while(loop<power) {
            result = result.multiply(new BigInteger("8"));
            loop++;
            multiply(result,loop,power);
        }
        System.out.println(result);
    }
}

问题核心原因

你的代码同时混用了while循环和递归调用,这是导致重复输出的关键:

举个例子,假设你输入的power值为2,我们一步步拆解执行流程:

  1. 首次调用multiply(1, 0, 2),进入while循环(0<2):
    • 计算得result=8,loop=1
    • 递归调用multiply(8, 1, 2)
  2. 进入递归的multiply(8,1,2),再次进入while循环(1<2):
    • 计算得result=64,loop=2
    • 递归调用multiply(64,2,2)
  3. 这次调用中loop=2不满足loop<power,跳过循环直接执行System.out.println(64)——第一次输出
  4. 回到上一层递归方法,此时while循环条件不满足,退出循环后执行System.out.println(64)——第二次输出
  5. 回到最外层方法,同样退出循环后执行System.out.println(64)——第三次输出

简单来说:每一层递归调用结束后,当前方法都会执行一次System.out.println(result),而非只有最底层的递归才输出,最终导致结果被多次打印。

修复方案

你需要二选一:要么用循环实现,要么用递归实现,不要混合使用:

方案1:仅用循环实现

import java.util.*;
import java.math.BigInteger;
class THIRTYSEVEN {
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        BigInteger a = new BigInteger("1");
        multiply(a, 0, sc.nextInt());
    }
    static void multiply(BigInteger b, int loop, int power) {
        BigInteger result = b;
        while(loop < power) {
            result = result.multiply(new BigInteger("8"));
            loop++;
        }
        // 循环结束后仅打印一次结果
        System.out.println(result);
    }
}

方案2:仅用递归实现

import java.util.*;
import java.math.BigInteger;
class THIRTYSEVEN {
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        BigInteger a = new BigInteger("1");
        BigInteger result = multiply(a, 0, sc.nextInt());
        // 仅在主方法中打印最终结果
        System.out.println(result);
    }
    static BigInteger multiply(BigInteger b, int loop, int power) {
        // 递归终止条件:达到指定幂次时返回当前值
        if (loop >= power) {
            return b;
        }
        // 递归调用,每次将数值乘8,循环计数+1
        return multiply(b.multiply(new BigInteger("8")), loop + 1, power);
    }
}

两种方案都能保证结果只打印一次,符合你的预期。

内容的提问来源于stack exchange,提问作者Neil D'cruze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:37:53