#include <iostream>
#include <math.h>
usingnamespace std;
int prime(int n);
int main() {
int i;
for (i = 2; i <= 50; i++) {
if (prime(i))
cout << i << " is prime" << endl;
else
cout << i << " is not prime" << endl;
}
cout << "Press RETURN to continue...";
cin.get();
return 0;
}
int prime(int n) {
int i;
double sqrt_n = sqrt(static_cast<double>(n));
for (i = 2; i <= sqrt_n; i++) {
if (n % i == 0) // If i divides n evenly,
returnfalse; // n is not prime.
}
returntrue;
}
What I was trying to do is basically reverse this and just have two nested For loops without the function. I realize the function is better, but I'm trying to refresh my brain on how to do this and for some reason it's eluding me.
#include <iostream>
#include <math.h>
usingnamespace std;
int main() {
int i;
for (i = 2; i <= 50; i++) {
int j;
double sqrt_i = sqrt((double)i);
for (j=2;;j++) {
if(j>sqrt_i){
cout << i << " is prime" << endl;
break;
}elseif (i % j == 0){ // If j divides i evenly,
cout << i << " is not prime" << endl;//it's not prime
break;
}
}
}
cout << "Press RETURN to continue...";
cin.get();
return 0;
}
The two parts I was missing was calculating the sqrt of i (which I previously had done but then talked myself out of it thinking it was a bone head move lol) and comparing the nested count to the sqrt_i.
I should have just continued to listen to that annoying little voice in my head.
Again, thanks for the help, I can now sleep in peace lol.