Every line of 'simple prime number program in python' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.
20 def prime(num): 21 # num is actually a string because input() returns strings. We'll convert it to int 22 num = int(num) 23 24 if num < 0: 25 print("Negative integers can not be prime") 26 quit() 27 if num is 1: 28 print("1 is neither prime nor composite") 29 # See how I lazily terminated program otherwise it'd forward "None"(default behaviour of python when function 30 # returns nothing) rather than True or False. Which could mess up the program. 31 # If we hit this if statement above statement is printed then program exits. 32 quit() # Now you don't need to get sys.exit() to exit python has quit to handle the same thing 33 if num in [2, 3]: 34 # if given argument is 2 or 3, it is prime. We used list without defining a variable which is perfectly valid 35 return True 36 if num % 2 == 0: # excluding all even numbers except two. 37 return False 38 else: 39 # Here we are starting counter variable from 3 in range. Second argument excludes numbers above one third 40 # of the given argument. Third argument in range sets steps to take to 2. This makes loop to iterate odds 41 for x in range(3, int(num/3), 2): 42 # Checking if argument is divisible by counter. % is modulus operator which returns remainder of division 43 if num % x == 0: 44 return False 45 # It's okay to have more than one return statement when program hits return statement it exits the function. 46 return True
746 def prime_number_factorisation(n): 747 if n < 2: 748 return [n] 749 i = 2 750 factors =  751 while i * i <= n: 752 if n % i: 753 i += 1 754 else: 755 n //= i 756 factors.append(i) 757 if n > 1: 758 factors.append(n) 759 return factors