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)
Related
I have to count the sum of all prime numbers that are less than 1000 and do not contain the digit 3.
My code:
def primes_sum(lower, upper):
total = 0
for num in range(lower, upper + 1):
if not num % 3 and num % 10:
continue
elif num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
total += num
return total
total_value = primes_sum(0, 1000)
print(total_value)
But still I don't have right result
def primes_sum(lower, upper):
"""Assume upper>=lower>2"""
primes = [2]
answer = 2
for num in range(lower, upper+1):
if any(num%p==0 for p in primes): continue # not a prime
primes.append(num)
if '3' in str(num): continue
answer += num
return answer
The issue in your code was that you were checking for num%3, which checks whether num is divisible by 3, not whether it contains a 3.
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 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
I have been trying to make a 'Prime Number Checker' that looks like this:
Please enter a number: 7
The factors are:
1
7
7 is a prime number
Try again? Y
Enter a number: 6
The factors are:
1
2
3
6
6 is not a prime number
It has 6 factors
I am stuck on the very last portion, which counts how many factors a non-prime number has (listed as 'num_factors' in the code below). Thank you! *Edited for clarity.
def main():
num = int(input("Please enter an integer between 2 and 5,000: "))
def list_factors(x):
print("The factors of your number are: ")
for i in range(1, x + 1):
if x % i == 0:
print(i)
list_factors(num)
def is_prime(num):
if num>1:
for i in range(2,num):
if (num%i) == 0:
print(num, "is NOT a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
is_prime(num)
def num_factors(x):
for i in range(1, x + 1):
if x % i == 0:
list = []
print("It has", len(list), "factors")
num_factors(x)
print()
again=input("Try again? (y/n): ")
if again == "y":
print()
main()
else:
print("Bye!")
if __name__ == "__main__":
main()
I suggest you build a list of factors first, instead of iterating at each step.
def get_factors(n):
factors = []
for i in range(1, n+1):
if n % i == 0:
factors.append(i)
return factors
Now you can define your other functions in terms of the list of factors:
def is_prime(factors):
return len(factors) == 2
def num_factors(factors):
return len(factors)
If you want to make your implementation more efficient, I suggest you read up on prime factorization.
a=int(input("Enter number: "))
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print("Number is prime")
else:
print("Number isn't prime")
Change
def num_factors(x):
for i in range(1, x + 1):
if x % i == 0:
list = []
print("It has", len(list), "factors")
num_factors(x)
for
def num_factors(x):
list = []
for i in range(1, x + 1):
if x % i == 0:
list.append(x)
print("It has", len(list), "factors")
num_factors(num)
Your number is called num, not x. Then you should create the factor list outside the for loop and append each factor to the list.
As somebody recommended in the comments, you should print outside of the functions. Also you don't need to check for factors bigger than x//2. So I would recommend something like this:
def num_factors(x):
list = []
for i in range(1, x//2 + 1):
if x % i == 0:
list.append(x)
return facts
facts=num_factors(num)
print("It has", len(facts), "factors")
You were very close, the only adjustment would be that you would want to append those values that pass if x % i == 0 which can also be stated if not x % i: and you would want to move the empty list outside of your loop. then just return the length of that list.
def num_factors(non_prime):
l = []
for i in range(1, non_prime+1):
if not non_prime % i:
l.append(i)
return len(l)
print('It has {} factors'.format(num_factors(10)))
# It has 4 factors.
Future References:
Just to open you to why it would be important to explore built in functions, you could accomplish this using filter in one expression
def num_factors(non_prime):
return len(list(filter(lambda x: not non_prime % x, range(1, non_prime +1))))
As well as with list comprehension
def num_factors(non_prime):
return len([i for i in range(1, non_prime +1) if not non_prime % i])
You can find information on both at https://docs.python.org/3/
# input and validation integer number
try:
num = int(input(
"Please enter an integer number between 2 and 5,000 : "))
except ValueError:
print("Please enter an integer number between 2 and 5,000!!!")
# for check number.
# If number is prime it's true
# If number not prime it's false
# default is true
status = True
print("%d divided by %d" % (num, 1))
for i in range(2, int(num / 2)+1):
if num % i == 0:
status = False
print("%d divided by %d" % (num, i))
print("%d divided by %d" % (num, num))
if status:
print("%d is prime" % (num))
else:
print("%d is not prime" % (num))
If you would like to capture all the factors, you could use the sub below. If you give it a number like 1024, it returns a list of ten 2's (all the factors)
def main():
x = int(input('Enter a number to find the prime factors '))
primes = prime_factors(x)
print(primes)
def prime_factors(x):
factors = []
y = 2
while (y <= x):
while x % y != 0:
y += 1
x /= y
factors.append(y)
return factors
main()
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()