def prime(upper):
while upper >=2:
for num in range(2, upper + 1):
prime = True
for i in range(2, num):
if (num % i == 0):
prime = False
if prime:
print(num, end=",")
if num == upper: #I think there is a problem here
break
prime(7)
How can I stop this function when it reachs 7 value
PS: I want to execute this codes with while loop.
BTW if you can make it this codes without for-loop please do it for me :)
I appreciate you...
EDIT:
I guess my previous is_prime function is problematic. This way is quicker and works well:(Source)
def is_prime(n):
""""pre-condition: n is a nonnegative integer
post-condition: return True if n is prime and False otherwise."""
if n < 2:
return False;
if n % 2 == 0:
return n == 2 # return False
k = 3
while k*k <= n:
if n % k == 0:
return False
k += 2
return True
You should use this function.
BEFORE EDIT:
I would use the is_prime function from here. You can use another way.
And, I would suggest this code for you:
def is_prime(Number):
return 2 in [Number, 2**Number%Number]
def prime(upper):
print([num for num in range(2, upper + 1) if is_prime(num)])
prime(7)
Output:
[2, 3, 5, 7]
But if you insist on using only while loop, you can modify your prime function as:
def prime(upper):
num = 2
while num <= upper:
if is_prime(num):
print(num, end = ",")
num += 1
Then, output will be:
2,3,5,7,
Related
I've worked a lot on this but I can't figure out the problem. Can you help me?
The code should print numbers from 0 to 100 and print next to the prime numbers "Prime". The first function works but if I try to print the numbers all togheter the "prime" tag gets misplaced.
def testPrime(numTest):
if numTest <= 1:
return False
if numTest == 2:
return True
for i in range(2, numTest):
if (numTest % i) == 0:
return False
else:
return True
def printPrimes (lenght):
i = 0
while i <= lenght:
if testPrime(i):
print(str(i) + "Prime")
else:
print(str(i))
i += 1
printPrimes(100)
The logic in testPrime() is flawed. There are faster techniques but here's a trivial approach that may help:
def testPrime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5)+1, 2):
if n % i == 0:
return False
return True
Since a prime number is defined a number a natural number greater than 1 that is not a product of two smaller natural numbers
I think this is the only lines you need.
def testPrime(n):
for i in range(2,n):
if n%i == 0:
return False
return True
I'm trying to make a relatively efficient piece of Python code that will sum all the primes under 2 million, but this code doesn't seem to work. It regards numbers like 9 and 15 prime for some reason:
sum = 2
for num in range(3, 2000000, 2):
for i in range(2, 1+int(num**0.5)):
if num % i == 0:
break
sum += num
print(sum)
As written, your code ignores the checks in the inner for loop, and sums the current number regardless of whether or not it's a prime or not.
Either use a flag variable:
prime_sum = 2
for num in range(3, 2000000, 2):
is_prime = True
for i in range(2, 1+int(num**0.5)):
if num % i == 0:
is_prime = False
break
if is_prime:
prime_sum += num
print(prime_sum)
or use the for loop's else clause (which only runs after the loop runs to completion - ie. no break):
prime_sum = 2
for num in range(3, 2000000, 2):
for i in range(2, 1+int(num**0.5)):
if num % i == 0:
break
else:
prime_sum += num
print(prime_sum)
You're not checking whether the inner loop found a factor or not before adding num to sum.
You can use the else: block of a loop to tell whether the loop finished or stopped due to break.
sum = 2
for num in range(3, 2000000, 2):
for i in range(2, 1+int(num**0.5)):
if num % i == 0:
break
else:
sum += num
print(sum)
You're breaking out of the inner loop if the number is not prime, but then are still executing the line
sum += num
There are multiple solutions to this.
Moving the primality test to a function
def is_prime(x):
for i in range(2, int(x ** 0.5) + 1):
if x % i == 0:
return False
return True
sum = 2
for num in range(3, 2000000, 2):
if is_prime(num):
sum += num
print(sum)
is_prime variable
sum = 2
for num in range(3, 2000000, 2):
is_prime = True
for i in range(2, 1+int(num**0.5)):
if num % i == 0:
is_prime = False
break
if is_prime:
sum += num
print(sum)
all() and a list comprehension
sum = 2
for num in range(3, 2000000, 2):
if all([num % i != 0 for i in range(int(x ** 0.5) + 1)]):
sum += num
print(sum)
In Python 3, I am trying to write a function that counts the number of prime number in a list, can anyone help me with that?
def function(x):
array = []
aa = len(x)
for num in x :
if (num == 1 or num ==2):
array.append()
elif num >2:
for i in range (2, aa):
if (num % i )== 0:
array.append()
else:
print (num)
array.append(num)
return len(array)
z = [4,5,6,7,8,9,10]
print (function(z))
but it shows an incorrect result!
Here is my fix of your code.
def count_primes_in_list(numbers):
primes = []
for num in numbers:
if num == 2:
primes.append(num)
else:
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print (num)
primes.append(num)
return len(primes)
z = [4, 5, 6, 7, 8, 9, 10]
print (count_primes_in_list(z))
I'll note a few things for beginners to know. Don't use reserved or type like words for methods and variables, name things descriptively. Change function to count_primes_in_list, array to primes, x to numbers and so on. Your test for a prime is incorrect. A prime is a number greater than 1 that can not be divided by another number greater than 1 and less than its self. In python don't put () around if tests.
Your logic is a little wrong and I'm not sure what you think array.append() is supposed to. And the len(x) is irrelevant. Note: 1 is not prime.
You can use the else: clause to the for loop, this means only execute if the for loop completes so if you break out early it does not get executed. So if the num is divisible by any number break else: add to array.
def function(x):
array = []
for num in x:
if num <= 1:
continue
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
array.append(num)
return len(array)
In []:
z = [4, 5, 6, 7, 8, 9, 10]
print(function(z))
Out[]:
5
7
2
Note: there are many more efficient methods for checking primality but this is good enough for small numbers.
def countPrime(num):
d=0
for n in num:
if n>1:
for i in range(2,n):
if (n%i)==0:
break
else:
d+=1
return d
if __name__ == '__main__':
num=[]
cot=int(input())
for i in range(cot):
numbers.append(int(input()))
print(countPrime(num))
prime number count in python list
def countPrimeNumbers(numbers):
count=0
for num in numbers:
if(num<2):
continue
else:
for i in range(2,num):
if(num%i==0):
break
else:
count+=1
return count
I'm a beginning programmer in python and have a question about my code I'm writing:
number = int(input("Enter a random number: "))
for num in range(1, number + 1) :
for i in range(2, num) :
if (num % i) == 0 :
break
else :
print(num)
break
When I run this program I also get 9, 15 21 as output. But these are not prime numbers.
What is wrong with my code?
Thanks!
With if (num % i) == 0: you go to the else block for every num, which is not a multiply of 2, as you start i with 2, thus printing num. I got all odd numbers printed with your code.
You can use something like this:
number = int(input("Enter a random number: "))
for num in range(1, number + 1):
prime = True
for i in range(2, num):
if (num % i) == 0:
prime = False
break
if prime:
print(num)
It sets prime to False when it encounters a divisor without rest.
the trouble is in your else: statement which has to run outside of the first loop. I recommend the following:
def isprime(num):
for i in range(2, num):
if (num % i) == 0:
return False
return True
for num in range(1, number + 1) :
if isprime(num):
print num
Your problem
The else statement that you put inside the for loop means that if that number(num) is divisible by this current no represented by i, return true considering it as a prime which IS NOT CORRECT.
Suggestion
Your outer loop starts with 1 which should change to 2, as 1 is not a prime number
Solution
def fun(number):
#Not counting 1 in the sequence as its not prime
for num in range(2, number + 1) :
isPrime = True
for i in range(2, num) :
if (num % i) == 0 :
isPrime = False
break
if isPrime:
print num
fun(10)
Output
1
2
3
5
7
I am assuming the random number is the range you want the numbers to be within.
I found that the variable i is always equal to 2 in your code.This destroys the purpose of having a second for loop
Prime numbers are numbers that cannot be divisible by 2, 3 or 7, excluding 2, 3 or 7!
With this knowledge I adapted your code to show the true prime numbers.
solution
number = int(input("Enter a random number: "))
for num in range(2,number +1) :
printnum = True
if num == 2:
printnum = True
elif num == 3:
printnum = True
elif num == 7:
printnum = True
elif num % 2 == 0:
printnum = False
elif num % 3 == 0:
printnum = False
elif num % 7 == 0:
printnum = False
if printnum == True:
print(num)
This is my method to generate first ten prime numbers with no imports, just simple code with components we are learning on college. I save those numbers into list.
def main():
listaPrim = []
broj = 0
while len(listaPrim) != 10:
broj+= 1
brojac = 0
for i in range(1,100):
if broj % i == 0:
brojac += 1
if brojac == 2:
listaPrim.append(broj)
print(listaPrim)
if __name__=='__main__':
main()
I wrote a code in python to find the nth prime number.
print("Finds the nth prime number")
def prime(n):
primes = 1
num = 2
while primes <= n:
mod = 1
while mod < (num - 1):
ptrue = 'true'
if num%(num-mod) == 0:
ptrue = 'false'
break
mod += 1
if ptrue == 'true':
primes += 1
return(num)
nth = int(input("Enter the value of n: "))
print(prime(nth)
The code looked fine to me, but it returns an error when I run it:
Traceback (most recent call last):
File "C:/Users/AV/Documents/Python/nth Prime.py", line 17, in <module>
print(prime(nth))
File "C:/Users/AV/Documents/Python/nth Prime.py", line 13, in prime
if ptrue == 'true':
UnboundLocalError: local variable 'ptrue' referenced before assignment
It appears to me as if it is trying to say that I am referring to ptrue in the last line even though I am not. What is the problem here... Can anyone help?
how about using Boolean ? and initalize ptrue out of while loop
print("Finds the nth prime number")
def prime(n):
primes = 1
num = 2
while primes <= n:
mod = 1
ptrue = True
while mod < (num - 1):
if num%(num-mod) == 0:
ptrue = False
break
mod += 1
if ptrue == True:
primes += 1
return(num)
nth = int(input("Enter the value of n: "))
print prime(nth)
ptrue is local to your while loop which goes out of scope as soon as the while loop ends. so declare ptrue before the start of your inner while loop
Get rid of ptrue entirely and use else with your inner loop. For example:
while mod < (num - 1):
if num % (num - mod) == 0:
break
mod += 1
else:
primes += 1 # only executes if loop terminates normally, without `break`
You can try this:
#This program finds nth prime number
import math
def is_prime(number):
if number < 2:
return False
if number % 2 == 0:
return False
else:
for i in range(3, number):
if not number % i:
return False
return True
n = input('Enter n: ')
#This array stores all the prime numbers found till n
primes = []
for i in range(100000):
if is_prime(i):
primes.append(i)
if len(primes) == n:
break
print("nth prime number is: " + str(primes[n-1]))
The first part is define a function that calculates the next prime number given any number.
import math
def is_prime(x): # function
for i in range(2,int(math.sqrt(x))+1):
if x%i == 0:
return is_prime(x+1)
return x
For example, is_prime(10) will return 11.
The next step is to write a generator that returns a list of prime numbers.
def get_prime(k): # generator
cnt = 1
n = 2
while cnt <= k:
yield(is_prime(n))
n = is_prime(n) + 1
cnt += 1
For example, get_prime(5) will return [2,3,5,7,11].
The code below can help you test the results.
a = get_prime(50)
lists = list(a)[:]
for idx, value in enumerate(lists):
print("The {idx}th value of prime is {value}.".format(idx = idx+1, value = value))
All answers depends on user input, but here is a simple code to give nth number, no matter how big the n is ....
def isprime(n): # First the primality test
if n<2:
return False
for i in range(2,n):
if n%i==0:
return False
break
else:
return True
def nthprime(n): # then generic code for nth prime number
x=[]
j=2
while len(x)<n:
if (isprime(j)) == True:
x.append(j)
j =j+1
print(x[n-1])
n=int(input('enter n'))
a=[2,3,5,7]
i=3
j=9
while i<n:
flag=0
j=j+2
for k in range(len(a)):
if (a[k]<=int(j**0.5) and j%a[k]==0):
flag=1
break
if flag==0:
a=a+[j]
i=i+1
print(a[n-1])
Try this.
n = int(input())
count=1
u=2
prime=[]
while(count<=n):
temp=0
for i in range(2,u):
if(u%i==0):
temp=1
if(temp==0):
count+=1
prime.append(u)
u+=1
print(prime[-1])
Program to find nth Prime Number.
def nth_Prime(num):
Semi = num*num
Res_1 = [True for i in range(Semi+1)]
prime = 2
while prime*prime <= Semi:
if Res_1[prime] == True:
for i in range(prime*prime, Semi+1, prime):
Res_1[i] = False
prime += 1
Res_2 = []
for i in range(2, Semi+1):
if Res_1[i]:
Res_2.append(i)
return Res_2[num-1]
if __name__ == "__main__":
num = int(input("Enter nth Number: "))
print(nth_Prime(num))
Try this out ,I just made few changes in yours.
Here I am checking for each prime number using all(num%i!=0 for i in range(2,num)) checking its remainder not equal to zero so if it is true for that range (starting from 2 and less than itself) it is a prime and for that all() function helps me later if its a prime I increment the 'p' count and check till 'p' is less than the 'n'(Input Number) so when it equates the condition its the nth prime we are looking for.
n=raw_input("enter the nth prime ")
num=4
p=2
while p <int(n):
if all(num%i!=0 for i in range(2,num)):
p=p+1
num=num+1
print "nTH prime number: ",num-1