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

Becrowd 1161题提交100%答案错误,本地运行正常求排查

题目要求

无限读取两个数M和N,计算并输出它们的阶乘之和,注意结果可能超过15位。
输入:包含多组测试用例,每组为两个整数M(0≤M≤20)和N(0≤N≤20),以EOF结束输入。
输出:每组测试用例输出一行,内容为M和N的阶乘之和。

我的问题

我编写了如下JavaScript代码,在VSCode中运行正常,但提交至Becrowd后显示100%答案错误,请问问题出在哪里?

// this the code i have writen but it says 100% wrong answar.
// On the other hand i check the code in vscode, it is work properly
// Then what was wrong 

var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var lines = input.split('\n');
var line = lines.shift().split(" ");
const M = parseInt(line[0]);
const N =parseInt(line[1]);
const fact = (M,N)=>{
    let s1 = 1;
    let s2  =1;
    if(M===0)
        s1 = 1;
    else{
        for(let i =1; i<=M; i++)
            s1=s1*i;
    }
    if(N===0)
        s2 = 1;
    else{
        for(let j =1; j<=N; j++)
            s2=s2*j;
    }
    const sum = s1+s2;
    return sum;
}
const result = fact(3,2);
console.log(result);
问题分析与修正

你的代码存在以下几个致命问题:

  • 仅处理一组测试用例:题目要求处理多组输入直到EOF,但你只读取了第一行数据,没有循环遍历所有输入行,完全忽略后续测试用例。
  • 硬编码测试参数:调用fact(3,2)时直接用固定值,根本没用到读取到的M和N,代码完全脱离输入数据运行。
  • 大数精度丢失:20的阶乘为2432902008176640000,超过了JavaScript Number类型的精确范围(2^53),用Number计算会导致精度错误,必须用BigInt处理大数运算才能保证结果准确。
  • 未处理空行:输入中可能存在空行,直接处理会导致解析错误,需要跳过无效空行。

修正后的代码:

const input = require('fs').readFileSync('/dev/stdin', 'utf8');
const lines = input.split('\n');

// 用BigInt实现阶乘,保证大数精度
const factorial = (num) => {
    let result = 1n;
    const bigNum = BigInt(num);
    for (let i = 1n; i <= bigNum; i++) {
        result *= i;
    }
    return result;
};

// 遍历所有行处理多组测试用例
for (const line of lines) {
    const trimmedLine = line.trim();
    // 跳过空行
    if (!trimmedLine) continue;
    
    const [M, N] = trimmedLine.split(' ').map(Number);
    const sum = factorial(M) + factorial(N);
    // 转换为字符串输出,避免BigInt的格式问题
    console.log(sum.toString());
}

内容的提问来源于stack exchange,提问作者Jobayer Ahmad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 22:33:37