Back story: I have a test tomorrow and my teacher usually makes us type a code from scratch. This time, he typed a code during class while we watched on the projector, then printed the code out for us to study and told us this would be the code we need to type for the test and to know it exactly. The code is suppose to take an lower bound and upper bound and display all the prime numbers in between them.
Well, about an hour ago I typed the program up multiple times, exactly as it is printed on the paper, and the output is incorrect. I don't know if i keep repeatedly typing it wrong, or if he typed it up too fast in class and messed up. here's the code:
#include<iostream>
#include<cstdlib>
#include<cmath>
usingnamespace std;
bool isPrime(int n)
{
staticbool *testPrime = NULL;
staticint testSize = 0;
int i;
int k;
if(n > testSize)
{
if(testPrime) delete [] testPrime;
testPrime = newbool[n + 1];
testSize = n;
for(i = 0; i <= testSize; i++) testPrime[i] = false;
testPrime[1] = true;
for(i = 1; i <= (testSize + 1) / 2; i++)
{
if(testPrime[i]) continue;
k = i + i;
while(k <= n)
{
testPrime[k] = true;
k += i;
}
}
}
if(testPrime[n]) returnfalse; elsereturntrue;
}
int main()
{
int i;
unsignedint lowerBound, upperBound;
do
{
cout << "- Enter a lower bound >= 3 : "; cin >> lowerBound;
} while(lowerBound < 3);
do
{
cout << "Enter an upper bound greater the lower bound : "; cin >> upperBound;
} while(upperBound <= lowerBound);
for(i = lowerBound; i <= upperBound; i++)
{
if(isPrime(i)) cout << i << " is prime" << endl;
}
cin.clear();
cin.get();
return 0;
}
- Enter a lower bound >= 3 : 20
Enter an upper bound greater the lower bound : 100
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
#include<iostream>
#include<cstdlib>
#include<cmath>
usingnamespace std;
bool isPrime(int i)
{
int k, N;
if(i <= 1) returnfalse; else N = sqrt(i);
for(k = 2; k <= N; k++) if(i % k == 0) returnfalse; returntrue;
}int main()
{
int i;
unsignedint lowerBound, upperBound;
do
{
cout << "- Enter a lower bound >= 3 : "; cin >> lowerBound;
} while(lowerBound < 3);
do
{
cout << "- Enter an upper bound greater the lower bound : "; cin >> upperBound;
} while(upperBound <= lowerBound);
for(i = lowerBound; i <= upperBound; i++)
{
if(isPrime(i)) cout << i << " is prime" << endl;
}
cin.clear();
cin.get();
return 0;
}
- Enter a lower bound >= 3 : 20
- Enter an upper bound greater the lower bound : 100
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime