Objectives
- familiarizing the student with classic notions and algorithms;
- improving the student's skills in defining and using functions.
Scenario
A natural number is prime if it is greater than 1 and has no divisors other than 1 and itself.
Complicated? Not at all. For example, 8 isn't a prime number, as you can divide it by 2 and 4 (we can't use divisors equal to 1 and 8, as the definition prohibits this).
On the other hand, 7 is a prime number, as we can't find any legal divisors for it.
Your task is to write a function checking whether a number is prime or not.
The function:
is called is_prime;
takes one argument (the value to check)
returns True if the argument is a prime number, and False otherwise.
Hint: try to divide the argument by all subsequent values (starting from 2) and check the remainder - if it's zero, your number cannot be a prime; think carefully about when you should stop the process.
If you need to know the square root of any value, you can utilize the ** operator. Remember: the square root of x is the same as x0.5
Complete the code in the editor.
Run your code and check whether your output is the same as ours.
Expected output
2 3 5 7 11 13 17 19
Before we create our function, let's know what is a prime number first.
Prime Number
- It's a whole number/integer that is greater than 1.
- It's factors (multiplication factors) are 1 and itself ONLY. Different than this, then it's not a prime.
- If squared (3 ** 0.5) doesn't equal a whole number.
- Prime % 2 = 1
- Except 2, prime numbers are odd numbers (prime % 2 = 1)
3 has only two factors (1 x 3)
5 has only two factors (1 x 5)
4? (1 x 4, 2 x 2) .. 4 % 2 = 0 .. 4 ** 0.5 = 2 4 is NOT prime
Solution with Code
Is there other sophisticated solutions? When you go up and read again the definition and rules for prime numbers, we can come up with a better faster solution
=================================================================================
0 Comments
Your opinion matters, your voice makes us proud and happy. Your words are our motivation.