Friends i have little bit problem in making a c language program.
I have to make a program which prints prime numbers from 1 to 500.
I make this program but with while loop then i was told to make it using for loop, which i tried but failed.
So kindly help me. Thanks
from,
john(pakistan)
john_hasan 0 Newbie Poster
Recommended Answers
Jump to PostI dont know that high math, but I think I can do better.
bool isPrime(int n) { bool prime ; int lim; if ( n == 0 || n == 1 || n % 2 == 0) return(false); prime = true; lim = (int)sqrt(n); for(int i=3; i<= …
Jump to PostI wouldn't call 2 a special case - it fits the general description perfectly; A number evenly divisible only by 1 and itself
Strictly that's not true because 1 is divisible by 1 and itself, but 1 isn't prime. I prefer:
A prime number has precisely two positive integer …
Jump to PostThis should be considerably although I'd bet not noticeably faster.
#include <iostream> using namespace std; int main (){ int prim=3, div,i=2; cout<<1<<" "<<2<<" "; for (i; i<=500; i++){ div=3; while(div<=prim/3){ if (prim%div!=0){div+=2;} else {prim+=2;div=3;}} cout<<prim<<" "; prim+=2;} system("pause");}
Why do you care about the speed anyways?
Jump to PostWhy do you care about the speed anyways?
If the developers didnt care for speed then u wouldn't be conviniently using your favourite OS u are usign right now without atlest swearing atleast 100 times a day regarding the slow loading times.
Dont forget that this is a C/ …
Jump to PostTo "optimize" it a little further without getting too technical you could keep track of each prime along the way. Then to check if current number is prime just check to see if previous primes up to the square root of the current number are a factor rather than checking …
All 37 Replies
Micko 2 Junior Poster
john_hasan 0 Newbie Poster
hollystyles 113 Veteran Poster
Salem 5,265 Posting Sage
hollystyles 113 Veteran Poster
Salem 5,265 Posting Sage
shavez_israr 0 Newbie Poster
Salem 5,265 Posting Sage
hollystyles 113 Veteran Poster
hollystyles 113 Veteran Poster

iamthwee
hollystyles 113 Veteran Poster
dude543 2 Light Poster
hollystyles commented: good solution +2
Salem 5,265 Posting Sage
hollystyles commented: good feedback +2
hollystyles 113 Veteran Poster
hollystyles 113 Veteran Poster
dude543 2 Light Poster
hollystyles 113 Veteran Poster
Bench 212 Posting Pro
hollystyles 113 Veteran Poster
portege 0 Light Poster
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster
portege 0 Light Poster
WolfPack 491 Posting Virtuoso Team Colleague
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster
portege 0 Light Poster
WolfPack 491 Posting Virtuoso Team Colleague
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster
Lerner 582 Nearly a Posting Maven
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.