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
Related
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
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
so pretty straight forward, I had to write a code to check if a number if Prime or not. Code tested on Jupyter Notebook and works PERFECTLY. But whenever I put it in CodeWars, it passes the initial tests but later on when I submit the attempt, it times out, saying that the code may be "inefficient". Does anyone have an insight as to why this might be happening? Here is the code:
def is_prime(num):
mylist = []
if num != 1 and num > 0:
for number in range(1,num+1):
if num % number == 0:
mylist.append(number)
else:
pass
if len(mylist)>2:
return False
else:
return True
else:
return False
For large numbers, your time to compute will take too long.
I suggest looking more into the properties of prime numbers and reevaluating your code.
Ex: Properties of Prime Numbers!
can you try this and see how it works in CodeWars.
for num in range(1,7):
if all(num%i!=0 for i in range(2,num)):
print('Prime' , num)
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
I am learning programming from scratch first time in my life. I am learning the Python language. My first difficult task is to write algorythm which checks if the number is the prime number.
The script should work in very simple way. You enter:
is_prime(29)
and you should get output like this:
The number 29 is the prime number.
or
The number 29 is NOT the prime number.
I did not check any solution on the internet. I did it by myself. My assumptions was as follows:
from the school I remember that the prime number is divided only by 1 and by itself
'0' and '1' are not the prime number
So I wrote the code which checks if the given number is divided by all numbers from 2 to (number-1). For example if the given value is '6', the script checks first if the 6 is divided by 2. If this is true that means the number is NOT a prime number. If 6 would be not divided by 2, the script checks if 6 is divided by 3. If so, that means the number is NOT a prime number. In case of '7'number the script checks 7/2, then 7/3, then 7/4 then 7/5, then 7/6.
The code is like this:
def is_prime(number):
if number == 0 or number == 1:
print(f"The number {number} is NOT the prime number.")
elif number == 2:
print(f"The number {number} is the prime number.")
else:
for i in range(2, number):
if number % i == 0:
check = "is NOT"
break
else:
check = "is"
print(f"The number {number} {check} the prime number.")
But then, I actually realized three things:
If the number is divided by 2, definitely it is not the prime number
If the number is not divided by 2, it can be divided by 3 or by 5.
If the number is not divided by 2, is not divided by 3 and is not divided by 5 that means that this number is the prime number. The only exceptions from this rules are these three numbers 2,3 and 5.
And that's it. So I wrote the code as follows
def is_prime(number):
if number > 1:
if (number %2 == 0 and number != 2) or (number %3 == 0 and number != 3 ) or(number %5 == 0 and number != 5):
print(f"The number {number} is NOT the prime number. ")
else:
print(f"The number {number} is the prime number. ")
else:
print(f"The number {number} is NOT the prime number. ")
I think that both solutions are ok. Please correct me if I am wrong
But I would like to ask you which solution is better from the programming point of view?
Even though your first is correct and the second is not, you would gain speed in the algorithm by:
Don't try to test for divisibility if the number you are trying
to divide with is already a factor of the previous numbers, e.g.
when you have tried to divide with 2, you only need to try odd
numbers. If a number is not divisible by 2, it is clearly not
divisible by 4.
You only need to test up to the square root of
the number. At least one of the factors needs to be less than or
equal to the square root.
Your original code looks correct. The second one doesn't rule out numbers like 49.
One more thing about my first solution which you confirmed is correct.
The range to check inside the 'for' loop is:
for i in range(2, number)
But correct me if I am wrong, I think that it is enough to have range = (2, number/2)
For example let us consider the number 541 which is the prime number. My code will check modulo as follows:
541/2
541/3
541/4
.
.
.
541/538
541/539
541/540
But it is completely useless to check dividors greater than value 270 (which is almost the half of 541). If the 541 is not divided by 270 , it is obvious that it can not be divided by 271, 272, 273, 274, 275 and so on.
So I think it is enough to have:
for i in range(2, round(number/2)+1)
I had to add + 1 because otherwise I get error when I run the function for the number 3.
What do you think?
Am I right that it is enough to have range for check (2, number/2) instead of (2, number) ?
def is_prime(number):
count = 0
for i in range(1,number+1):
if number%i == 0:
count +=1
if count == 2:
print('The number {0} is the prime number.'.format(number))
else:
print('The number {0} is NOT the prime number.'.format(number))