In this post I'm going to go over how to create a function that will determine whether a number is prime and a function that prints all the prime numbers under it(and the number itself if it's a prime number).
This task might seem a little difficult for beginners to programming, but it actually just requires a little thinking and that's it, and a teeny tiny bit of math.
I'm not a math genius so I might not get it.
Trust me, it's a lot easier than you think.
Every prime number except for 2 and 3 follow a specific pattern. the number above or below it is divisible by 6.
Yeah, but can't normal numbers fall under this?
So not all prime numbers follow this rule?
No, all prime numbers do follow this rule, but every once in a while other numbers that aren't prime can have this trait.
Well, 25 isn't a prime but 24 is divisible by 6. So that's one that's early on.
So, how do we get rid of them?
Based on my math it seems that all of these stragglers are powers of 2, 3, 5, 7, and 11.
What about the other prime numbers?
We don't need to worry about them, the cross filtering of the 6 rule and the power rule will create an exact method.
I don't understand.
In simple terms all we have to do is make two functions, one for the 6 rule and another for the power rule(there are other ways to get prime numbers, this isn't the only way).
Let me show you what it'd look like in a few languages.
Wow, that was easy!
So, now that we know know how to determine whether the input is a valid prime number we can use the functions just presented to generate prime numbers.
Hold on, our functions only return a boolean value how does that help?
Quick recap: boolean logic is for making decisions(that's how if statements work), so if a number is prime both functions will return true.
So we can iterate it over each number in the given range and add it to a list. Once that's done we can print each number to see the results.
Okay, but how do we do that?
I'll show you.
Okay what's going on?
Okay, what about the second method?
For C++ I made a while loop and called the findingprimes function and the ispower function on the given number, if it's prime it gets printed if not it is skipped. Then "num" is decreased by one and the proccess repeats untill num is equal to zero.
Hope you learned something!