Write a method that takes in an integer (greater than one) and returns true if it is prime; otherwise return false.
Definition of a prime number: whole numbers greater than 1 that can only be divided by 1 and itself without remainder. (When divided by other whole numbers, it has a remainder.) Examples: 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29
Has remainder = prime (number % i != 0)
Has no remainder = not prime (number % i == 0)
Second time solving this, I learned a lot of things:
- Original solution doesn’t include edge case of 2 being the input number. However, it would still return true because 2 doesn’t fit the requirements to enter the while loop, and would skip to the next line, which is “return true”.
- Always return true or false in a boolean, not nil.
- Store your boolean in a variable, like not_prime, to make it more readable and easier to keep track of.
- You almost always want to return false first in the if statement. (Because you want to end the program as soon as possible.)
If number is not_prime, increment to ensure it’s still not_prime (has no remainder) when divided by the next whole number.
Also, number % i == 1 does NOT mean it has a remainder. It means it has a remainder of 1.