Prime Numbers

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)

Screen Shot 2016-08-19 at 3.01.45 PM

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.)

screen-shot-2016-09-19-at-11-41-16-pm

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.

Advertisements
Prime Numbers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s