I have been working through Jumping into C++ and in Chapter 5 one of the problems was to write a program that computes the first 100 prime numbers. With everything we have learned in the book this was not possible.
I emailed Alex and he gave me a clue in the formula lhs - (lhs / rhs) * rhs. This would make is a "fakeModulus". I used this and only have one problem. It does not work on the number 2. Other than that it compiles and works perfect.
Does anyone have an idea on this or is it just an imperfect formula for the number 2?
Please critique my code and let me know if I could improve it. The deal is I could only use loops as this is all we have been taught in the book. Also, I could not use the sqrt function so on the prime numbers I looped it that many times. Example: 541 looped 539 times as I did not check for 1 or 541.
Thanks,
Mike
Code:#include <iostream> // Write a program that computes the first 100 prime numbers. // Do this while only using loops. using namespace std; int main() { int prime_qty = 0; int prime_check = 0; cout << "How many prime numbers do you need? "; cin >> prime_qty; for ( int i = 1; i < prime_qty + 1; i++) { for ( int j = 2; j < i; j++) { prime_check = i - ( i / j ) * j; if (prime_check == 0) { break; } } if ( prime_check != 0) { cout << i << "\n"; } else { prime_qty++; } } }