[英]Why can't I find Sum() of this HashSet. says “Arithmetic operation resulted in an overflow.”
I was trying to solve this problem projecteuler,problem125 我正在尝试解决这个问题projecteuler,problem125
this is my solution in python(just for understanding the logic) 这是我在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)
the same code I wrote in C# is as follows 我在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());
}
}
}
the code debugs fine until it gives an exception at Console.WriteLine(found.Sum());
代码调试良好,直到在
Console.WriteLine(found.Sum());
给出异常为止Console.WriteLine(found.Sum());
(line31). (第31行)。 Why can't I find
Sum()
of the set found 为什么我不能找到
Sum()
的一组发现
The sum is: 2,906,969,179. 总和为:2,906,969,179。
That is 759,485,532 greater than int.MaxValue; 比int.MaxValue大759,485,532;
Change int
to long
in var found = new HashSet<long>();
将
int
更改为long
var found = new HashSet<long>();
To handle the value. 处理值。
You can also use uint
however instead of long
, however I would recommend using long
. 您也可以使用
uint
代替long
,但是我建议使用long
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.