Why does my prime number code time out on CodeWars? - python

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)

Related

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

any() in python coding issue

I am trying to make a function that tells you if a number is prime or not using the any() method. This is what I have:
def prime(n):
if any(n % i == 0 for i in range(1, n + 1)) != True:
print("Prime")
else:
print("Not Prime")
prime(5)
However it is giving me:
Not Prime
every single time, even when I give a prime number.
Can someone please help me out?
Everything is divisible by 1, so that check will consider everything as non-prime. You need to set the lower bound to check to 2 instead.
As pointed out in the comments by #ForceBru, the upper bound is incorrect as well. You don't want to check if n is divisible by itself, since it always will be.
Change your range in the comprehension to just:
range(2, n))

creating a python program which ask the user for a number - even odd

I am new to python and I am taking a summer online class to learn python.
Unfortunately, our professor doesn't really do much. We had an assignment that wanted us to make a program (python) which asks the user for a number and it determines whether that number is even or odd. The program needs to keep asking the user for the input until the user hit zero. Well, I actually turned in a code that doesn't work and I got a 100% on my assignment. Needless to say our professor is lazy and really doesn't help much. For my own knowledge I want to know the correct way to do this!!! Here is what I have/had. I am so embarrassed because I know if probably very easy!
counter = 1
num = 1
while num != 0:
counter = counter + 1
num=int(input("Enter number:"))
while num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
There are a couple of problems with your code:
You never use counter, even though you defined it.
You have an unnecessary nested while loop. If the number the user inputs is even, then you're code will continue to run the while loop forever.
You are incorrectly using the else clause that is available with while loops. See this post for more details.
Here is the corrected code:
while True:
# Get a number from the user.
number = int(input('enter a number: '))
# If the number is zero, then break from the while loop
# so the program can end.
if number == 0:
break
# Test if the number given is even. If so, let the
# user know the number was even.
if number % 2 == 0:
print('The number', number, 'is even')
# Otherwise, we know the number is odd. Let the user know this.
else:
print('The number', number, 'is odd')
Note that I opted above to use an infinite loop, test if the user input is zero inside of the loop, and then break, rather than testing for this condition in the loop head. In my opinion this is cleaner, but both are functionally equivalent.
You already have the part that continues until the user quits with a 0 entry. Inside that loop, all you need is a simple if:
while num != 0:
num=int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
I left out the counter increment; I'm not sure why that's in the program, since you never use it.
Use input() and If its only number specific input you can use int(input()) or use an If/else statement to check
Your code wasn't indented and you need to use if condition with else and not while
counter = 1
num = 1
while num != 0:
counter = counter + 1
num = int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
Sample Run
Enter number:1
Odd 1
Enter number:2
Even 2
Enter number:3
Odd 3
Enter number:4
Even 4
Enter number:5
Odd 5
Enter number:6
Even 6
Enter number:0
Even 0

My program is not printing out the message I want

I have written a prime number program and I'm having a trouble with printing out the message "Neither prime nor a composite" as below. I think my code is fine as it is. I'd highly appreciate any comment on this issue. Thank you, in advance
def prime_number():
a = input("Please enter a number:")
x = True
s = 0
for i in range(2, a):
while x:
if a%i == 0:
x = False
elif s:
print s,"Neither a prime nor a composite"
else:
x = True
if x:
print a,"is a prime number."
elif s:
print s,"Neither a prime nor a composite"
else:
print a,"is not a prime number."
prime_number()
Your variable s will stay equall to 0 which is equall to False forever, so there is no way that Your code is going to print "Neither a prime nor a composite"
Just like Chantwaffle said, you'll never get s equal to anything else than 0, because there's no code changing it to anything else. Also, if a <= 2 you'll never enter this for loop, and elif s is always False, since s is defined as 0 at the beginning. Rewrite that code thinking of what you want to achieve and what should be done to get it. Repair logic of this code.

Categories