how to find all the prime numbers using loops. i ve made a program using for loop but it doesnt print the required stuff. i ve built a logic but its hard to put it into program.
Show us what you wrote?
if its not doing the right thing, the algorithm is probably wrong.
the algorithm is simple but if you don't know it, would take a bit of thinking to re-create.
one way to do it is have a container of Booleans from your start to end point, representing all the possible values. you can do it with ints but it takes up 64 times as much space so you can't do as many values before running out of space. A compromise is char, which can hold (more than)3 values (true, false, prime below) as letters and is handy for reasonably small lists, using 8 bits per value.
then you go through that counter picking numbers.
you pick 2 because you know the primes start there, and you then mark every Boolean in that container to true if it can be divided by 2.
so for up to 10, that looks like this:
2 3 4 5 6 7 8 9 10
P F T F T F T F T
now you pick the next true value in your container that isn't false, and call it prime: that is 3 do the same thing again: set everything divisible by 3 to false.
2 3 4 5 6 7 8 9 10
P P T F T F T T F
repeat, next value that isn't true is 5:
2 3 4 5 6 7 8 9 10
P P T P T F T T T
repeat for 7 and its done:
2 3 4 5 6 7 8 9 10
P P T P T P T T T
the first few primes are 2,3,5,7
c++ syntax you may not know: x%y == 0 tells you that y is a factor of x.
i saw my friend's code. He has written the same way but my issue is placing IF statements in FOR loops. as you can see there are two FOR loops i couldnt figure out which IF statement would be in which FOR loop.
I gave you the answer, its the same about of code give or take a couple lines, but you instead took your friend's code (which is a contender for the slowest, worst version of it I have ever seen) and posted that rather than write 10 lines of your own code. You risk you and your friend for cheating if its not allowed to share, on top of it. Our profs took the average of copied homework from 2 cheaters over 4 (each person gets 1/2 credit with that). I wonder if they still do that...