Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def old_is_prime(num):
- # You only need to go up to sqrt(num) rather than num/2
- for i in range(0, num//2):
- # You're only checking for divisibility by two
- if (num % 2) == 0:
- return False
- # You don't need an else; after the first iteration, the function ALWAYS returns
- else:
- return True
- # Instead return after the loop goes through every case
- # Improved version
- def new_is_prime(num):
- if num <= 2:
- return False
- for i in range(2, int(num ** (1/2)) + 1):
- if num % i == 0:
- return False
- return True
- # Compact and functional approach
- def compact_is_prime(num):
- return all(num % i != 0 for i in range(2, int(num ** .5) + 1))
- # Don't ask the user to pick the range, you should check it in the function
- num = int(input("Input an integer greater than 1: "))
- if compact_is_prime(num):
- print("{:d} is a prime".format(num))
- else:
- print("{:d} is not a prime".format(num))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement