|
| 1 | +## 7.1 Check Prime: |
| 2 | + |
| 3 | +### S-1: The problem |
| 4 | +For a given number, check whether the number is a prime number or not. |
| 5 | + |
| 6 | +### S-2: Hint |
| 7 | +A number is a prime number. If that number is only divisible by 1 and the number itself. |
| 8 | + |
| 9 | +This means a prime number is not divisible by any numbers between 1 and the number itself. |
| 10 | + |
| 11 | +So, to check prime, you can start dividing the number from 2. And then increase it by 1. If the number gets divided, then it’s not a prime number. |
| 12 | + |
| 13 | +### S-3: The solution |
| 14 | + |
| 15 | +```python |
| 16 | +def is_prime(num): |
| 17 | + for i in range(2,num): |
| 18 | + if (num % i) == 0: |
| 19 | + return False |
| 20 | + return True |
| 21 | + |
| 22 | + |
| 23 | +num = int(input("Enter a number: ")) |
| 24 | + |
| 25 | +check_prime = is_prime(num) |
| 26 | + |
| 27 | +if check_prime: |
| 28 | + print('Your number is a Prime') |
| 29 | +else: |
| 30 | + print('Your number is not a Prime') |
| 31 | +``` |
| 32 | + |
| 33 | +[try it: button] |
| 34 | + |
| 35 | +### S-4: Explanation |
| 36 | +The core part of the algorithm is the is_prime function. |
| 37 | + |
| 38 | +There we start a for loop the range(2, num). Because we want to know that the number is not divisible by any number except 1 or the number itself. |
| 39 | + |
| 40 | +For example, 29. It’s only divisible by 1 or 29. |
| 41 | + |
| 42 | +So, to test whether the number is divisible by any number greater than 1. We started the for loop from 2. And then going to before the num variable. |
| 43 | + |
| 44 | +To check the number divisible, we check the remainder to be equal to 0. If the number is gets divided, the remainder will be 0. |
| 45 | + |
| 46 | +So, if the number gets divided by, it’s not a prime number. That’s why we will return False. |
| 47 | + |
| 48 | +If the number doesn’t get divided by any numbers smaller than the number, it won’t go inside the if block. It will finish all the numbers up to the num. |
| 49 | + |
| 50 | +Then we will return True. Because it didn’t get divided, by any numbers. Hence, it will be a prime number. |
| 51 | + |
| 52 | +### S-5: Many Solution |
| 53 | +There are other solutions to this problem as well. We encourage you to google, “check prime number python”. In that way, you will learn a lot. |
| 54 | + |
| 55 | +### S-6: Take Away |
| 56 | +A prime number is only divisible by 1 and the number itself. |
| 57 | + |
| 58 | + |
| 59 | +[](..README.md) |
| 60 | + |
| 61 | + |
| 62 | +###### tags: `programmig-hero` `python` `float` `int` `math` |
0 commit comments