I have array of 3 digit prime numbers:
for num in range(100, 1000):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
numere_prime.append(num)
the list is:
numere_prime = [[101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163...]
What I need is multiply each digits of a number (ex 101 = 1 * 0 * 1) and then it shows all numere_prime that after multiplying is equal to user input. what i made so far:
for elem in numere_prime:
digits = [int(x) for x in str(elem)] # split digits into [1,0,1][1,0,3]...
for n in list(digits):
// n * n_at_next_index * n_at_next_index
if //result of multiplying == //number set by input:
//append digits to result list
result should be like:input (9) = [191, 313, 331, 911]
CodePudding user response:
Your prime algorithm is wrong. You can't just append to list when ANY factor fails, you have to know that ALL of the factors fail. And you don't have to search all the way to num
; you only have to search up through sqrt(num)
. Since the largest value is 1000, you can stop at 33. Also, it's silly to check for num > 1
since you start the range at 100. And you don't have to convert digits
to a list; it's already a list.
You could make this a bit shorter by using the any
function inside get_primes
, and by using yield
in the filter_primes
. You'll get to that later.
def get_primes():
numere_prime = []
for num in range(100, 1000):
prime = True
for i in range(2, 34):
if (num % i) == 0:
prime = False
break
if prime:
numere_prime.append(num)
return numere_prime
def filter_primes(primes, magic):
res = []
for elem in primes:
digits = [int(x) for x in str(elem)]
product = 1
for n in digits:
product *= n
if product == magic:
res.append(elem)
return res
numere_prime = get_primes()
inp = int(input("Your value: "))
result = filter_primes(numere_prime, inp)
print(result)
CodePudding user response:
primes = [101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163]
a = int(input('enter a nmber :'))
primes_useful = []
for i in primes :
product = 1
for k in str(i):
product *= int(k)
if product == a :
primes_useful.append(i)
print(primes_useful)
CodePudding user response:
numere_prime = []
for num in range(100, 1000):
prime = True
for i in range(2, num):
if (num % i) == 0:
prime = False
if prime:
numere_prime.append(num)
def prime_digit_prod(x):
output = []
for elem in numere_prime:
digits = [int(x) for x in str(elem)] # split digits into [1,0,1][1,0,3]...
result = 1
for n in digits:
result *= n
if result == x:
output.append(elem)
return output
print(prime_digit_prod(9))
output:
[191, 313, 331, 911]
CodePudding user response:
numere_prime = [101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157]
digi_mult_dict = {}
for elem in numere_prime:
c = elem % 10
b = int((elem % 100 - c)/10)
a = int((elem - b - c)/100)
mult = a * b * c
digi_mult_dict[elem] = mult
numero = input("input a number")
for key, value in digi_mult_dict.items():
if int(value) == int(numero):
print(key)