Prime numbers
Why does my code print so many of the same prime number?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
{
int num;
cout << endl << "Please enter an integer larger than 50: ";
cin >> num;
cout << endl;
while (num <= 50)
{
cout << "You have entered a value less than 50. ";
cout << "Please enter a valid value: ";
cin >> num;
}
int a[20];
ofstream outfile;
outfile.open("Random.txt");
for(int i = 0; i < 20; i++)
{
outfile << rand()%(num) + 1 << endl;
}
outfile.close();
ifstream infile;
infile.open("Random.txt");
while(infile >> num)
{
//if(num == 1)
for(int i = 2; i < num - 1; ++i)
{
if(num % i == 0)
{
//nothing
}
else if (num % i != 0)
{
cout << num << endl;
}
}
}
infile.close();
return 0;
}
| |
Removing some of your code to make things simpler to test:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <sstream>
using namespace std;
std::istringstream in("4 6 8");
int main()
{
unsigned num;
while (in >> num)
{
std::cout << "Processing " << num << '\n';
//if(num == 1)
for (unsigned i = 2; i < num - 1; ++i)
{
if (num % i == 0)
{
//nothing
}
else if (num % i != 0)
{
cout << num << endl;
}
}
std::cout << "Done processing " << num << '\n';
}
}
|
Processing 4
Done processing 4
Processing 6
6
Done processing 6
Processing 8
8
8
8
Done processing 8 | |
What does your code have to do with primes? ;)
I know that loop keeps executing even though I don't need it to anymore, I just don't know how to stop it.
Topic archived. No new replies allowed.