I just finished one of my problems for school which is simply asking the user to enter an integer and then outputs if the int is prime or not. I used an if else statement to determine if a number is even or odd, because all odd numbers are prime. The only even prime number is the number 2. So, I then added an extra true false statement that if the int == 2, it outputs that it's also prime. I like to check my work when I'm done and see what other people did which usually yields similar programs as mine or maybe I'll learn something new, etc. So my question is basically this: My program works and it seems it effectively states if numbers are prime or not. However, I noticed pretty much everyone else's programs I've looked at use a for statement like "for (int i = 2; i < n; i++)" and then the if else statement similar to mine.
Can my program be just as effective without the aforementioned for loop? I keep second guessing myself, but the for loop is just to keep repeating until it yields false, so it seems (for my program) that it isn't really necessary, but I just want to make sure I don't have any potential loopholes (no pun intended).
samedi 3 décembre 2016
Determining if an integer is prime
Inscription à :
Publier les commentaires (Atom)
Aucun commentaire:
Enregistrer un commentaire