Console Based - Prime Number Display
To continue with my C++ console projects I thought it would be fun to make a prime number program. The aim is for the user to type in a limit number, ie 900, and then for the program to count to that number and discard any numbers that aren't prime. (prime meaning a number with exactly 2 factors).
The code
The code is written in such a way where it thinks the number is prime until "proven" otherwise. A sort of guilty until proven innocent idea.
The pre-processor commands are nothing out of the ordinary. "stdafx.h" was included since I use Microsoft Visual Studio and <iostream> was included for it's console writing functionality.
First the user is asked for an integer. This will become the variable c. The first for loop the compiler will encounter creates a variable called "count" and give it the value 2 (since 2 is the first prime number) and it specifies that only if "count" is lower or equal to "c" it may compile what is inside it's braces. First the Boolean variable "prime" is created and given the value "true" or 1, then the next for loop starts.
In this for loop an integer called "potfactor" is created and given the value 2. And the contents of this for statement can only be used if "potfactor" is less than "count". Then the for loop would test if a number had any factors that weren't one or itself. This was done using the "%" operator. This operator produces the remainder if "count" would be divided by "potfactor" and if this remainder equals 0 then "potfactor" must be a factor. Since it goes into the "count" without any remainder. After this is completed "potfactor" is incremented by one and the test for a factor is repeated until "potfactor" cannot increase without becoming equal to "count". At this point the "count" increments by one, as a result of the first for loop, and this number is then tested for factors ("potfactor" returns to 2). If any value of "count" manages to come out with no factors the reassignment of "prime" to false will not happen and it will be printed to the console window. However if at any time a value of "count is found to have a factor then it will not be printed to the window.
Here is the whole thing in table format in case my limited explanation skills are confusing anyone.
Downloads
The code I wrote is available for download here.
I liked this project because it involved some complex thinking and it allowed me to practice using for loops in a useful scenario.
Thanks and until next time.
No comments:
Post a Comment