15/6 is_prime


#1

This is my code:

def is_prime(x):
....n = 2
....if x < 2:
........return False
....elif x == 2:
........return True
....else:
........while n < x:
............result = x % n
............n = n + 1
............if result == 0:
................return False
............else:
................return True

It fails as "result == 0" returns False on the first iteration. How do I edit it to first check x with all the values of n and then return True or False.


#2

For starters, make it readable by others. All it takes is three little back-ticks before and after your code (on separate lines) and we can see all the indentation and keyword highlighting. You really should try it!

```

That's all it takes.


#3

Instead of going to all this trouble,

def is_prime(x):
....n = 2
....if x < 2:
........return False
....elif x == 2:
........return True
....else:
........while n < x:
............result = x % n
............n = n + 1
............if result == 0:
................return False
............else:
................return True

you can have this...

def is_prime(x):
    n = 2
    if x < 2:
        return False
    elif x == 2:
        return True
    else:
        while n < x:
            result = x % n
            n = n + 1
            if result == 0:
                return False
            else:
                return True

Not saying the code is right, mind, just remarking at the visibility.


#4

We're taught quite early on about the special meaning of prime numbers, but then it is dropped and not brought up again until much higher up the learning curve. Educators are not to blame if we didn't learn factorization. It's taught at every level from middle school on up.

Factorization would have taught us a number of things:

  1. A number only divisible by itself and 1 is a prime.
  2. No prime has even parity.
  3. By the commutative property, all factors must pivot around the square root.

This is enough information to construct a factoring engine to find all primes.


#5

Why are we trying to find prime numbers? It comes back to factorization. Every number can be shown as a product of primes, each to varying degrees. This is called prime factorization. By finding the factors we find patterns and properties of whatever we are studying. As earlier mentioned, primes have a special meaning, and only by thinking about it do we begin to see it. Patterns take on a whole new meaning when we begin to see the primality of their origins.