C# Why can't I find Sum() of this HashSet. says "Arithmetic operation resulted in an overflow."
- by user2332665
I was trying to solve this problem projecteuler,problem125
this is my solution in python(just for understanding the logic)
import math
lim=10**8
found=set()
for start in xrange(1,int(math.sqrt(lim))):
sos = start*start
for i in xrange(start+1,int(math.sqrt(lim))):
sos += (i*i)
if sos >= lim: break
s=str(int(sos))
if s==s[::-1]:
found.add(sos)
print sum(found)
the same code I wrote in C# is as follows
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()); (line31). Why can't I find Sum() of the set found