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))
Related
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 don't know why such an easy syntax result in mistake. Can anyone help me to see if I missed out any?
This part only tries to check if a particular (num) is prime or not.
Not sure why my check_primes(10) results into 'PRIME'. Cuz I'm looping through y from 3,4,5,6,...,9-> then 10%5==0, I suppose it returns true and 'Non PRIME' is the result.
Do I do any wrong in my loop?
def check_primes(num):
for y in range(3,num):
if num%y==0:
return 'Non PRIME'
else:
return 'PRIME'
A way to return 'PRIME' or 'Non PRIME' as in your example:
def check_primes(num):
is_prime = True
for y in range(3,num):
if num % y==0:
return 'Non PRIME'
else:
continue
return 'PRIME'
You will return 'Non PRIME' the moment you can verify the number is not prime. Alternatively if you succeed in all your checks, you will return 'PRIME' as desired.
(Note that this is not a very efficient way to get primes)
(Note also that the comment below is correct, this method works exactly the same way with or without the else clause)
The definition of "prime" states that a number is prime if and only if it is only divisible by 1 and itself. This means that a number is not prime if you find one number from 2 to n-1 which divides n. To check that a number is prime, you must check every number from 2 to n-1. Your code stops immediately after testing divisibility by 3 in both cases.
You should use print instead of return. You are breaking your loop when you return it.
I am new to coding, and I am trying to write a somewhat generic prime number program. The difference with mine is that I want my program to be more efficient and only check numbers equal to, and including the square root of the number being checked, and I only want it to check previously found prime numbers. So far I have accomplished only the first criteria.
from numpy import sqrt, ceil
for a in range (3, 10000):
k=0
b=ceil(sqrt(a))
for i in range(2, int(b))
if (a%i==0):
k=k+1
if(k<=0):
print(a)
I think that I need to create a list with the number 2, run the program, and append any prime numbers that are printed to the list. However, I do not know how to:
1.) Make sure only numbers on said list are checked.
2.) Make sure only numbers through sqrt(a) are checked.
Any guidance is appreciated
You want to remember the primes that have been found, so store them in a list rather than just printing them. You mention appending primes as they are found; to do use primes.append(new_prime). Use break once you find a factor or once you pass the square root to skip to the next iteration.
primes = [2]
for tested_number in range(3, 10000, 2): #skip the evens
is_prime = True # if this is still true after testing, number is prime
for prime in primes:
if tested_number%prime == 0:
is_prime = False
break
elif prime>sqrt(tested_number): # no need to check these primes
break
if is_prime:
primes.append(tested_number)
My code is a PYTHON program that identifies if a number is prime or not. When I entered 45 however, it said that 45 was a prime, even though 45 isn't a prime number. Also, every time I run the program, it prints 'Sorry, the number you have entered is not prime.' or 'The number is indeed prime!' multiple times, instead of once. How do I make it print the output statements once and how can fix the program so that it says 45 IS NOT a prime number.
n = eval(input("Enter a number to find if that number is prime: "))
a = 2
while n > a:
if ((n % a) == 0) & (a != n):
print('Sorry, the number you have entered is not prime.')
break
else:
print('The number you have entered is indeed prime!')
Because you are printing it every time. If you want to break after finding/not finding the prime number, indent one more level for the break.
Also, this does not calculate prime numbers. It calculates if its even number.
Follow the solution here
Your code has some issues. To start with, you're never updating a, so you only ever check if the number n is even.
Once you fix that, you have two indentation problems. The first is that the break line needs to be inside the body of the if statement. Indent it more so that it's inside the if block.
The second indentation issue is more subtle. If you leave the else where it is, it will print out that the number is prime every time you test a potential factor that doesn't divide the number. That's both unhelpful (since it prints a lot) and wrong (since it says the number is prime even if it will later find a factor and say it's not prime). You can fix this by unindenting the else line so that it is lined up with the while statement. Using an else after a loop is an obscure bit of Python syntax. The body of the else only runs if the condition of the loop fails. It gets skipped if the loop exits due to a break statement.
Here's all of those necessary fixes together:
while n > a:
if ((n % a) == 0) & (a != n):
print('Sorry, the number you have entered is not prime.')
break # indent this line more!
a += 1 # increment a, so you don't keep checking 2 over and over
else: # unindent this line (and the next line too)
print('The number you have entered is indeed prime!')
There are some other things that could be improved in your code, though they aren't causing it to run incorrectly. I'd recommend using int instead of eval to parse your number, and I'd use the logical-and operator and instead of the bitwise-and operator & in the if statement (though actually you don't need either, since the a != n check is redundant, as the loop would have already ended if it was true).
TASK : Write a program that prints out all the primes below 10,000.
Hint: you will need to use % which gives the remainder of a division operation.
So x=11%5 would give 1 as 11/5=2 remainder 1
I FOUND THIS CODE , can someone add annotations next to all the lines explaining what is happening.I totally don't understand this code.
numbers=[]
for i in range(0,10001):
numbers.append(" ") #We just put spaces in each box for now
numbers[0]="X"
numbers[1]="X"
firstFree=2
while firstFree<10001:
multiple=firstFree*2
while multiple<10001: #Mark all multiples of firstFree as X
numbers[multiple]='X'
multiple=multiple+firstFree
firstFree=firstFree+1
while firstFree<10000 and numbers[firstFree]=='X':
firstFree=firstFree+1
for i in range(0,10001):
if(numbers[i]!='X'):
print(i)
As you have been told, you should not learn that way. Plus, in my humble opinion, this code you have found is extremely ugly and hard to read.
This is beter example.
#Main loop, this is self explanatory.
for dividend in range(2, 10000):
#This loops through all divisors available.
for divisor in range(2, dividend):
#Check against reminder of division.
if dividend % divisor == 0:
#Prints all composites of prime number that failed against check.
print('{} equals {} * {}'.format(dividend, divisor, dividend//divisor))
#Breakes second loop.
break
#Find answer for this thing yourself. It is interesting.
else:
#Enters here when have not found division factor.
print('{} is one of the prime numbers.'.format(dividend))
Read tons of tutorials, train and learn.