Python - prime number algorithm doesn't work with higher numbers - python

I´m new at python and I have problem with my simple program.
I have found some simple algorithm that can tell if input number is prime number or not. Evrything works fine with input numbers like 2 or 13. The problem happens when I use higher number (and I need to use higher numbers only).
num = 3231817448941
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num, "is a prime number")
else:
print(num,"is not a prime number")
My number input is 3231817448941. Because this number is prime number it should print:
Output should be:
3231817448941 is a prime number
But after runing this program my concole is empty and nothing is printed.
Also when I use similar number with same length that is not prime number then it works.
As I said I'm new at python and I would appreciate any advice.

One change to speed up the process A LOT
num = 3231817448941
if num > 1:
for i in range(2,int(num**0.5)+1): # Dont have to check to n, just sqrt(n)
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num, "is a prime number")
else:
print(num,"is not a prime number")
You can find more optimizations here

Related

Python program which returns the properties of a number by choosing a random number in a given range? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
I want to create a function in which system takes a random number from the given range and tell us about it's properties like odd-even number, prime-composite number, positive-negative number. It would be good if it's in Python3
I have although created function but somehow its showing some errors during compiling
import random
A = eval(input("Enter the Range from: "))
B = eval(input("Enter the Range to: "))
num = random.randint(A,B)
if num>=1:
print(num,"is positive number")
if num%2==0:
print(num,"is even number")
else:
print(num,"is odd number")
if num >= 1:
for i in range(2,num+1):
if num%2i==0:
print(num,"is a composite number")
break
else:
print(num,"is a prime number")
elif num==0 or num==1:
print(num,"is neither prime nor composite")
else:
print(num,"is a prime number")
elif num==0:
print(num,"is neither positive nor negative")
print(num,"is neither even nor odd")
print(num,"is neither prime nor composite")
else:
print(num,"is negative number")
try this:
import random
A = int(input("Enter the Range from: "))
B = int(input("Enter the Range to: "))
def number_properties(start, end):
# Generate a random number from the given range
number = random.randint(start, end)
# Check if the number is odd or even
if number % 2 == 0:
odd_even = "even"
else:
odd_even = "odd"
# Check if the number is prime or composite
if number < 2:
prime_composite = "neither prime nor composite"
elif number == 2:
prime_composite = "prime"
else:
for i in range(2, number):
if number % i == 0:
prime_composite = "composite"
break
else:
prime_composite = "prime"
# Check if the number is positive or negative
if number < 0:
positive_negative = "negative"
elif number == 0:
positive_negative = "neither positive nor negative"
else:
positive_negative = "positive"
# Print the properties of the number
print(f"The number {number} is {odd_even}, {prime_composite}, and {positive_negative}.")
number_properties(A, B)

Inputting large numbers and check if it is prime (Python)

I am making a program using python wherein it checks large numbers if it is a prime number or not. (this is for RSA Encryption)
Here is my code:
p = int(input("Enter first prime number: "))
while(1):
if isPrime(p) is False:
print("%d is not a prime number!" % p)
p = int(input("Please enter first prime number again: "))
else:
print("%d is a prime number." % p)
break
q = int(input("Enter second prime number: "))
while(1):
if isPrime(q) is False:
print("%d is not a prime number!" % q)
q = int(input("Please enter second prime number again: "))
else:
print("%d is a prime number." % q)
break
p is the first large number and q is the second large number.
here is the function that checks if it is a prime number:
def isPrime(num):
if num > 1:
for i in range(2, num):
if(num % i) == 0:
return False
else:
return True
else:
return False
I tried running it using small numbers like 17 and 11 and it works but when I tried to input a 16-digit number, it doesn't work anymore.
Here is the sample run:
On the second image, when I entered a large number, it does not continue. I tried waiting for half an hour and see if it works but it still, it's just like that. Why is it so?
It's taking so long because you're looping over A LOT of numbers, every one up until your 16 digit one, which is a lot of loop iterations. Even if you're only doing constant work per iteration, getting through that many numbers will still take awhile. Loops in python are notoriously slow. Luckily, you can use sympy like so:
from sympy.ntheory import factorint
def isPrime(n):
return len(factorint(n)) == 1
and then things should be going much faster. For reference:
factorint(133453565475464563453)
took about half a second

Python program to print prime numbers

I have started learning python and I am stuck in this code
num=int(input("Enter the number"))
for i in range(2, num):
if num%i==0:
print("Not a prime number")
break
print("Prime Number")
When I enter the number which are not prime, then I am getting output as not a prime number but when I am entering the number that is prime I am getting the output as
Prime number
Prime number
Prime number
Prime number
Prime number
You should only print it once, for example like this:
num = int(input("Enter the number"))
for i in range(2, num):
if num % i == 0:
print("Not a prime number")
break
else:
print("Prime Number")
The loop should check for all numbers and only then print not prime for example like this.
num=int(input("Enter the number"))
for i in range(2, num):
if num%i == 0:
print("Not a prime number")
break
if i > num/2:
print("Prime Number")
break
I would suggest you debug by including print statements that would help a beginner.
check this out :
num=int(input("Enter the number"))
for i in range(2, num//2):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")`
The last statement should be managed carefully in this code. Due to this it print in loop and take care of the tabs you shift.

Stuck in an infinite loop with my prime number finder program

I've been working on a program for my class for a bit. It is supposed to be a prime number finder, where the def is_prime (num) function loops and continually asks the user to input more numbers, checks whether they are prime, and prints whether they are or not. If a negative number is entered, it is supposed to then quit.
def is_prime (num):
while num >= 0:
if num % 1 == num or num % num == 0:
print(num, "is a prime")
elif num % 2 == 0:
print(num, "is not a prime")
continue
elif num < 0:
print("Done. Thanks for using the program!")
break
return 0
if __name__ == "__main__":
print("This program checks if a given number is a prime number\n")
num1 = int(input("Please enter a positive number (or a negative number to exit):\n"))
is_prime(num1)
However, it only has part of that right. It reads and determines prime numbers...but instead of looping back to the function beginning it just endlessly prints the statement of whether or not it is a prime. I'm pretty sure it's a problem of where I've put my while loops, but I'm not entirely sure how to fix that.
Any help would be appreciated.
You haven't described your intended algorithm; it's not at all clear from your code. YOur first if checks whether the input number is divisible by 1 or divisible by itself ... both of which are algebraic tautologies.
Then you repeat this as long as the input remains positive. Since you never change the value of num, this is a pretty direct infinite loop.
You can't test for divisibility for each candidate factor with a different if in an if ladder.
You'll need to stash each prime you find in a list.
EG:
def sieve_primes(stop=100000):
"""Yield primes below stop."""
primes = [2]
for candidate in range(3, stop + 1, 2):
if not any(candidate % prime == 0 for prime in primes):
primes.append(candidate)
yield candidate
for prime in sieve_primes():
print(prime)
Raid it for ideas, but don't copy it verbatim. You could speed it up a lot with math.sqrt(), BTW.
HTH

A prime number checker that fails

It seems like a normal code and works well, but for whatever reasons when I try entering this number = 18765411123451, computer seems to freeze, any clue?
num = 18765411123451
if num > 1:
for i in range(2,num):
if num % i == 0:
print(num,"is not a prime number")
print("Because", i,"x",num//i, "=" ,num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
I've tried many other numbers and the code works as it should except that number. What happened here?
it freezes because your number just too high.
The reason is for i in range(2,num): with num = 18765411123451 with is 100 trillion...
Plus the fact that python 2 will try to allocate that memory just to create the list to iterate on it (in that case use xrange)
Good news: you don't have to check until the number itself, just check until square root (included):
for i in range(2,int(num**0.5)+1):
that's more reasonable (less that 5 million iterations) and will provide the same result.
Past the square root of a number, if you haven't found divisors, you won't find any afterwards (if q is a divisor of num, then p*q == num so either p or q has to be lower or equal than square root of num

Categories