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

Project Euler #1(HackerRank)解题求助:仅得60分测试用例报错

解决Project Euler #1在HackerRank上的测试用例错误问题

你的公式推导是正确的,问题出在整数溢出,这导致了大数值测试用例(即测试用例2、3)计算错误:

  • 代码中n使用int类型存储,当输入的数值较大时,n*n的结果会超出int的最大取值范围(约21亿),溢出后会得到错误的数值,最终导致求和结果偏差。

修改方案

将n的类型改为long,或者在计算时先将n转为long,确保乘法运算在更大的数值范围内进行,避免溢出。以下是两种可行的修改版本:

版本1:彻底使用long类型存储输入和中间值

using System;
class Solution {

    static void Main(String[] args) {
        int t = Convert.ToInt32(Console.ReadLine());
        long[] inputs = new long[t];
        for(int a0 = 0; a0 < t; a0++){
            inputs[a0] = Convert.ToInt64(Console.ReadLine()) - 1;
        }
        foreach (long item in inputs)
        {
            long n = item / 3;
            long s3 = 3 * (n * n + n) / 2;
            n = item / 5;
            long s5 = 5 * (n * n + n) / 2;
            n = item / 15;
            long s15 = 15 * (n * n + n) / 2;
            
            Console.WriteLine(s3 + s5 - s15);
        }
    }

}

版本2:仅调整中间变量n的类型

using System;
class Solution {

    static void Main(String[] args) {
        int t = Convert.ToInt32(Console.ReadLine());
        int[] inputs = new int[t];
        for(int a0 = 0; a0 < t; a0++){
            inputs[a0] = Convert.ToInt32(Console.ReadLine()) -1;
        }
        foreach (int item in inputs)
        {
            long n = item / 3;
            long s3 = 3 * (n * n + n) / 2;
            n = item / 5;
            long s5 = 5 * (n * n + n) / 2;
            n = item / 15;
            long s15 = 15 * (n * n + n) / 2;
            
            Console.WriteLine(s3 + s5 - s15);
        }
    }

}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 12:57:53