|
1 | 1 | # Prime number Determiner
|
2 | 2 | # replace input() with raw_input() in Python version 2.7 input() works with version 3
|
| 3 | +import math as Math |
3 | 4 |
|
4 |
| -while True: |
5 |
| - startOrEnd = str(input('Start or End : ')) |
6 |
| - if startOrEnd == 'Start': |
7 |
| - toCheckNum = int(input('Number to Check : ')) |
8 |
| - if toCheckNum > 1: |
9 |
| - for x in range(2, toCheckNum): |
10 |
| - if toCheckNum % x == 0: |
11 |
| - print(str(toCheckNum) + ' is divisible by ' + str(x)) |
12 |
| - print(str(toCheckNum) + ' is not a Prime number') |
13 |
| - break |
14 |
| - elif toCheckNum % x > 0: |
15 |
| - print(str(toCheckNum) + ' is a prime number') |
16 |
| - break |
17 |
| - continue |
18 |
| - else : |
19 |
| - print(str(toCheckNum) + ' is not a prime number') |
20 |
| - continue |
21 |
| - else : |
22 |
| - print('Progarm Ended...') |
23 |
| - break |
| 5 | +POSITIVE_MESSAGE = " is a prime number" |
| 6 | +NEGATIVE_MESSAGE = " is not a prime number" |
| 7 | + |
| 8 | + |
| 9 | +def is_number_prime(number): |
| 10 | + """ |
| 11 | + Function which checks whether the number is a prime number or not |
| 12 | + :param number: integer - to be checked for prime-ness |
| 13 | + :return: boolean - true if prime, else false |
| 14 | + """ |
| 15 | + |
| 16 | + """ |
| 17 | + This is the main logic behind reducing the numbers to check for as factors |
| 18 | + if N = a * b; where a<=b and a,b C (1, N) |
| 19 | + then, a * b >= a*a; |
| 20 | + which leads to => a*a <= N |
| 21 | + => a <= sqrt(N) |
| 22 | + Hence checking only till the square root of N |
| 23 | + """ |
| 24 | + upper_lim = Math.floor(Math.sqrt(number)) + 1 |
| 25 | + is_prime = True if number != 1 else False |
24 | 26 |
|
| 27 | + for i in range(2, upper_lim): |
| 28 | + if number % i == 0: |
| 29 | + is_prime = False |
| 30 | + break |
| 31 | + # The moment there is a divisor of 'number', break the iteration, as the number is not prime |
| 32 | + |
| 33 | + return is_prime |
| 34 | + |
| 35 | + |
| 36 | +while True: |
| 37 | + startOrEnd = str(input('Start or End : ')) |
| 38 | + if startOrEnd == 'Start': |
| 39 | + number = int(input('Number to Check : ')) |
| 40 | + result = str(number) |
| 41 | + prime_status = is_number_prime(number) |
25 | 42 |
|
| 43 | + if prime_status: |
| 44 | + result += POSITIVE_MESSAGE |
| 45 | + else: |
| 46 | + result += NEGATIVE_MESSAGE |
| 47 | + print(result) |
| 48 | + else: |
| 49 | + print('Program Ended...') |
| 50 | + break |
0 commit comments