printing prime numbers
Nov 13, 2017 at 8:02pm UTC
so basically the program prints the prime numbers for integers from 1 to 100. there should be 10 numbers per line which is fine but when it reaches 113 it skips a bunch of lines before the next line.
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
#include<iostream>
#include<math.h>
#include<stdio.h>
#include<fstream>
using namespace std;
bool isPrime(int num) {
for (int i = 2; i <= (sqrt(num)); i++) {
if (num%i == 0) {
return false ;
}
}
return true ;
}
int main() {
ofstream outfile; // output file with invalid values
string outfileName = "prime.txt" ;
int num;
outfile.open("prime.txt" );
while (1) {
cout << "Enter an integer between 1 and 100: " ;
cin >> num;
cout << endl;
cout << "The first " << num << " primes:" << endl;
outfile << "The first " << num << " primes:" << endl;
cout << endl;
if (num >= 1 && num <= 100) {
int count = 1;
int i = 2+1;
while (count < num) {
if (isPrime(i)) {
cout << i << " " ;
outfile << i << " " ;
count++;
}
if (count % 10 == 0) {
cout << endl;
outfile << endl;
}
i++;
}
break ;
}
else {
cout << "Invalid value " ;
}
}
system("pause" );
return (0);
}
Nov 13, 2017 at 8:54pm UTC
Line 39-42: You test count regardless of whether the iteration of the while loop produced a prime number. Move lines 39-42 to after line 37.
Nov 13, 2017 at 9:08pm UTC
unrelated but consider skipping even numbers in your check, as only 2 is prime of evens.
Nov 13, 2017 at 9:14pm UTC
that worked. thank you
Topic archived. No new replies allowed.