Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. def old_is_prime(num):
  2.     # You only need to go up to sqrt(num) rather than num/2
  3.     for i in range(0, num//2):
  4.         # You're only checking for divisibility by two
  5.         if (num % 2) == 0:
  6.             return False
  7.         # You don't need an else; after the first iteration, the function ALWAYS returns
  8.         else:
  9.             return True
  10.     # Instead return after the loop goes through every case
  11.  
  12. # Improved version
  13. def new_is_prime(num):
  14.     if num <= 2:
  15.         return False
  16.     for i in range(2, int(num ** (1/2)) + 1):
  17.         if num % i == 0:
  18.             return False
  19.     return True
  20.  
  21. # Compact and functional approach
  22. def compact_is_prime(num):
  23.     return all(num % i != 0 for i in range(2, int(num ** .5) + 1))
  24.  
  25. # Don't ask the user to pick the range, you should check it in the function
  26. num = int(input("Input an integer greater than 1: "))
  27.  
  28. if compact_is_prime(num):
  29.     print("{:d} is a prime".format(num))
  30. else:
  31.     print("{:d} is not a prime".format(num))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement