I want a list of n numbers and check each item for primality and log whether the given number is prime or not. Unfortunately my below shown code is working incorrectly and I need help finding out why is it happening.
My code snippet:
l1 = []
num = int(input("Enter a range of numbers :: "))
for i in range(2, num + 1):
l1.append(i)
for i in range(0, num - 1):
for j in range(2, num):
if l1[i] % j == 0:
print(f'{l1[i]} is not a prime ')
break
else:
print(f'{l1[i]} is a prime number')
The solution is to do the loop that check if the number is prime for
for j in range(2, l1[i]):
Because here num have nothing to do with the check if it's prime.
So the complete code is :
l1 = []
num = int(input("Enter a range of numbers :: "))
for i in range(2, num + 1):
l1.append(i)
for i in range(0, num - 1):
for j in range(2, l1[i]):
if l1[i] % j == 0:
print(f'{l1[i]} is not a prime ')
break
else:
print(f'{l1[i]} is a prime number')
For more info about algorithm to check if a number is prime, please refer to :
this post
Related
Write a function (say, sum_primes) in python3 that takes in a number and returns the sum of all primes less than or equal to that number.
I tried like:
def sum_primes(num):
total = 0
for i in range(2, num+1):
if num%i == 0:
break
else:
total += i
return total
sum_primes(11)
but doesn't work.
you can try this way:
#Take the input from user
upto = int(input("Find sum of prime numbers up to : "))
sum = 0
for num in range(2, upto + 1):
i = 2
for i in range(2, num):
if (int(num % i) == 0):
i = num
break;
#If the number is prime then add it.
if i is not num:
sum += num
print("\nSum of all prime numbers upto", upto, ":", sum)
I am a Python beginner.
I got a prime number within the specified range. However, I couldn't convert it to a list.
I also tried converting it to a string and back to a list.
import random
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
for num in range(lower,upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
Start with an empty list, and every time you find a prime number, append it to the list. Then you can print the list at the end:
nums = []
for num in range(lower,upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
nums.append(num)
print(nums)
Note that you only need to iterate up the square root of num, any factor beyond that can only have another factor which is less than it:
from math import sqrt
nums = []
for num in range(lower,upper + 1):
if num > 1:
for i in range(2, int(sqrt(num))):
if (num % i) == 0:
break
else:
nums.append(num)
print(nums)
I am pretty new to python, so I don't fully understand how to use loops. I am currently working on a piece of code that I have to find the first N prime numbers.
The result that is desired is if you input 5, it outputs 2, 3, 5, 7, and 11, but no matter what I input for 'max', the output always ends up being 2 and 3. Is there a way to improve this?
max=int(input("How many prime numbers do you want: "))
min=2
while(min<=(max)):
for c in range(2, min):
if min%c==0:
break
else:
print min
min=min+1
You only increment min in the else block, i.e., if min % c is nonzero for all c, i.e., if min is prime. This means that the code won't be able to move past any composite numbers. You can fix this by unindenting min=min+1 one level so that it lines up with the for and else.
number = int(input("Prime numbers between 2 and "))
for num in range(2,number + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
Solution: Get the nth prime number entry. Iterate through each natural numbers for prime number and append the prime number to a list. Terminate the program when length of a list satisfies the user nth prime number entry.
# Get the number of prime numbers entry.
try:
enterNumber = int(input("List of nth prime numbers: "))
except:
print("The entry MUST be an integer.")
exit()
startNumber = 1
primeList = []
while True:
# Check for the entry to greater than zero.
if enterNumber <= 0:
print("The entry MUST be greater than zero.")
break
# Check each number from 1 for prime unless prime number entry is satisfied.
if startNumber > 1:
for i in range(2,startNumber):
if (startNumber % i) == 0:
break
else:
primeList.append(startNumber)
if (len(primeList) == enterNumber):
print(primeList)
break
else:
startNumber = startNumber + 1
continue
Try that :
n = int(input("First N prime number, N ? "))
p = [2]
c = 2
while len(p) < n:
j = 0
c += 1
while j < len(p):
if c % p[j] == 0:
break
elif j == len(p) - 1:
p.append(c)
j += 1
print(p)
Its simple. Check the below code, am sure it works!
N = int(input('Enter the number: ')
i=1
count=0
while(count<N):
for x in range(i,i+1):
c=0
for y in range(1,x+1):
if(x%y==0):
c=c+1
if(c==2):
print(x)
count=count+1
i=i+1
The following code will give you prime numbers between 3 to N, where N is the input from user:
number = int(input("Prime numbers between 2, 3 and "))
for i in range(2,number):
for j in range(2,int(i/2)+1):
if i%j==0:
break
elif j==int(i/2):
print(i)
You can see to check a number i to be prime you only have to check its divisibility with numbers till n/2.
I have written a python code to find prime numbers between 2 and 30. But my code is not evaluating for 2 and 3. Can anyone tell me what is wrong in this code?
for i in range(2, 30):
for j in range(2, i-1):
if ((i % j) == 0):
print(i, "is not a prime number")
break
else:
print(i, "is a prime number")
break
The logic of your code is wrong. The else clause should be attached to the inner for loop, so it's only executed if the loop is exhausted without finding a divisor.
for i in range(2, 30):
for j in range(2, i-1):
if ((i % j) == 0):
print(i, "is not a prime number")
break
else:
print(i, "is a prime number")
Also note that the outer loop only runs up to 29, since the upper boundary is not included in a range. The inner loop does not include i - 1, but that's totatlly fine, since any non-trivial divisor is less than i - 1.
The inner loop won't be entered at all for 2 and 3, since the range will be empty in these cases. This is fine as well, since the else clause will be immediately entered.
for i in range(2, 30):
prime = True
for j in range(2, i-1):
if ((i % j) == 0):
prime = False
# print(i, "is not a prime number")
break
# else:
# print(i, "is a prime number")
# break
if prime:
print(i, "is a prime number")
else :
print(i, "is not a prime number")
There are lot of online link to solve the prime number problem. To improve yourself search yourself and understand the. Hope this and this link help you a lot. Happy codding
It isn't working because the nested for declaration:
for i in range(2, 30):
for j in range(2, i-1):
Uses range(2, i-1) and until i is 4, range returns no value:
i = 2 --> range(2, 1) # No value
i = 3 --> range(2, 2) # No value
i = 4 --> range(2, 3) # 2
This is because the range function returns values from the first parameter (included) to the second parameter (not included).
I want to decide that the numbers are primes or not, and if they are then append to a new list (called primes in my code).I have a nums=[], random-filled list.
for i in range(len(nums)-1):
for j in range(1,len(nums)-1):
if(nums[i]%j==0):
counter+=1
if(counter==2):
primes.append(nums[i])
Here's a cleaner way with an upper bound on the divisor.
primes = []
for num in nums:
for divisor in range(2, int(num ** .5) + 1):
if num % divisor == 0:
break
else:
primes.append(num)