为什么我找不到这个HashSet的Sum() ?表示“算术运算导致溢出”

本文关键字:表示 算术运算 溢出 找不到 HashSet Sum 为什么 | 更新日期: 2023-09-27 18:07:14

我正试图解决这个问题,问题125

这是我在python中的解决方案(只是为了理解逻辑)

lim = 10**8
total=0
found= set([])
for start in xrange(1,int(lim**0.5)):
    s=start**2
    for i in xrange(start+1,int(lim**0.5)):
        s += i**2
        if s>lim:
            break
        if str(s) == str(s)[::-1]:
            found.add(s)
print sum(found)

我用c#写的代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        public static bool isPalindrome(string s)
        {
            string temp = "";
            for (int i=s.Length-1;i>=0;i-=1){temp+=s[i];}
            return (temp == s);
        }
        static void Main(string[] args)
        {
            int lim = Convert.ToInt32(Math.Pow(10,8));
            var found = new HashSet<int>();
            for (int start = 1; start < Math.Sqrt(lim); start += 1)
            {
                int s = start *start;
                for (int i = start + 1; start < Math.Sqrt(lim); i += 1)
                {
                    s += i * i;
                    if (s > lim) { break; }
                    if (isPalindrome(s.ToString())) 
                    { found.Add(s); }
                }
            }
            Console.WriteLine(found.Sum());
        }
    }
}

代码调试得很好,直到在Console.WriteLine(found.Sum());处出现异常(第31行)。

为什么我找不到这个HashSet的Sum() ?表示“算术运算导致溢出”

为什么找不到集合的Sum()

总和为:2,906,969,179。

大于int.MaxValue;

将"var found = new HashSet<long>();"中的"int"修改为"long"处理

您也可以使用uint而不是long,但我建议使用long