Ask your own question, for FREE!
Computer Science 20 Online
OpenStudy (anonymous):

How to wap to print prime number form 1-100 in c

OpenStudy (anonymous):

Three ways: 1. int main () { for (int i=2; i<100; i++) for (int j=2; j*j<=i; j++) { if (i % j == 0) break; else if (j+1 > sqrt(i)) { cout << i << " "; } } return 0; } 2. int main () { for (int i=2; i<100; i++) { bool prime=true; for (int j=2; j*j<=i; j++) { if (i % j == 0) { prime=false; break; } } if(prime) cout << i << " "; } return 0; } 3. #include <vector> int main() { std::vector<int> primes; primes.push_back(2); for(int i=3; i < 100; i++) { bool prime=true; for(int j=0;j<primes.size() && primes[j]*primes[j] <= i;j++) { if(i % primes[j] == 0) { prime=false; break; } } if(prime) { primes.push_back(i); cout << i << " "; } } return 0; } Edit: In the third example, we keep track of all of our previously calculated primes. If a number is divisible by a non-prime number, there is also some prime <= that divisor which it is also divisble by. This reduces computation by a factor of primes_in_range/total_range. Taken from http://stackoverflow.com/questions/5200879/printing-prime-numbers-from-1-through-100

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!