I wrote a prime factorization program and it crashes in the while loop. I just get a "this program is not responding" message. The part in the while loop runs because it writes the messages to the screen, but nothing after it. The primes.txt file contains a list of all the prime numbers from 1 to 10000.
Here's the code:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
usingnamespace std;
int main()
{
int *primes;
int *array1;
ifstream inf ("primes.txt");
int c=1230;
primes = newint [c];
int iii=0;
for (int iii=0;iii<=c;iii++)
{
std::string Text;
getline(inf,Text);
stringstream convert(Text);
convert >> primes[iii];
}
int n=0;
array1 = newint [10000];
for (int iii=0;iii<=10000;iii++) array1[iii]=0;
cout<<"Type in a whole number between 1 and 10 000"<<endl;
cin>>n;
int remainder=n;
iii=0;
while (iii<=c)
{
if (remainder%primes[iii]==0)
{
cout<<"Found match:"<<iii<<";"<<primes[iii]<<endl;
remainder=remainder/primes[iii];
int num=primes[iii];
array1[num]++;
cout<<"array1[num] is now "<<array1[num]<<endl;
}
else
{
iii++;
}
}
cout<<"Printing results..."<<endl;
for (int iii=1;iii<=10000;iii++)
{
if (array1[iii]!=0) cout<<iii<<"^"<<array1[iii]<<endl;
}
return 0;
}
In the following code you are trying to access your array out of bounds:
1 2
array1 = newint [10000];
for (int iii=0;iii<=10000;iii++) array1[iii]=0;
Arrays in C/C++ start at zero and stop at size - 1. You are not stopping until size. You have this problem throughout your code. Normally when dealing with arrays in for loops you use the operator< not the operator<= and you start the loop at zero not one.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
usingnamespace std;
int main()
{
int *primes;
int *array1;
ifstream inf ("primes.txt");
int c=1230;
primes = newint [c];
int iii=0;
for (int iii=0;iii<c;iii++)
{
std::string Text;
getline(inf,Text);
stringstream convert(Text);
convert >> primes[iii];
}
int n=0;
array1 = newint [10000];
for (int iii=0;iii<10000;iii++) array1[iii]=0;
cout<<"Type in a whole number between 1 and 10 000"<<endl;
cin>>n;
int remainder=n;
iii=0;
while (iii<c)
{
if (remainder%primes[iii]==0)
{
cout<<"Found match:"<<iii<<";"<<primes[iii]<<endl;
remainder=remainder/primes[iii];
int num=primes[iii];
array1[num]++;
cout<<"array1[num] is now "<<array1[num]<<endl;
}
else
{
iii++;
}
}
cout<<"Printing results..."<<endl;
for (int iii=0;iii<10000;iii++)
{
if (array1[iii]!=0) cout<<iii<<"^"<<array1[iii]<<endl;
}
return 0;
}