Project Euler #50

http://projecteuler.net/problem=50

Hi, I'm trying to solve the problem on the above pg I'm using two set of codes

I'm using this one to generate Prime Numbers
#include <iostream>
#include <cmath>
#include <fstream>
#include <stdlib.h>
using namespace std;

int main(){
long long num,count=0;
bool prime;

ofstream outfile;
outfile.open("Prime Numbers.txt");

cout << "Please enter a positive integer to deduce all the prime numbers before it: " << endl;
cin >> num;

outfile<<2<<"\n";

cout<<2<<" is prime\n";

for(int i = 3; i <= num; i+=2)
{
prime = true;
for(int n = 2; n <=int(sqrt(i)); n++)
{
if(i % n == 0)
{
prime = false;
break;
}
}

if(prime)
{
count++;
cout<<i<<" is prime\n";
outfile<<i<<"\n";
}
if(count==600)
{
break;
}
}


cout<<"All prime numbers deduced have been save to the text file called Prime Numbers\n";
outfile.close();
cout<<'\a';
system("pause");
return 0;
}

I'm using this code to actually solve the problem

#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <sstream>
#include <cmath>
using namespace std;


int main()
{
ifstream infile;
infile.open("Prime Numbers.txt");
string read;
long long sum=0,num[600],i=0,tempt,j,n; bool prime;
for(i=0;i!=600;i++)
{
num[i]=0;
}
i=0;
while(infile.good())
{
infile>>read;
stringstream(read)>>tempt;
num[i]=tempt;
sum=sum+tempt;
i=i+1;
cout<<sum<<endl;
if(sum>=1000000)
{
break;
}
}

for(j=599;j!=-1;j--)
{
sum=sum-num[j];
prime = true;
for(int n = 2; n <=int(sqrt(sum)); n++)
{
if(sum % n == 0)
{
prime = false;
break;
}
}
if(prime==true)
{
break;
}
}
cout<<"The largest consecutive prime sum is: "<<sum<<"\n Number of terms = "<<j<<endl;
return 0;
}

If I restrict the sum to less than 100 I get the correct corresponding ans but not when I restrict it to less than 1000 or higher, can anyone tell me why.
I will greatly appreciate if the error can be found in this program rather than another be suggested. Thank you for your help
Well, this is a very messy and unoptimal code, but I won't elaborate on that :)
Problem might be is that your break statement
1
2
3
4
if(sum>=1000000)
{
break;
}

actually triggers and then when you access num[j] with j being for example 599, you access uninitialized memory containing garbage.
Topic archived. No new replies allowed.