[英]Print all n-digit numbers whose product of digits equals to given product python
enter image description here Display 3-digit prime numbers that have the product of digits equal to a given p-value.在此处输入图像描述显示 3 位素数,这些素数的数字乘积等于给定的 p 值。 Example: For p = 9 the numbers 191, 313, 331, 911 meet the conditions of the problem.示例:对于 p = 9,数字 191、313、331、911 满足问题的条件。
I found a code that does this just to find out their amount but not the product.我找到了一个代码,它只是为了找出它们的数量而不是产品。 I need to find out what I change in the program to find out the product, not the amount.我需要找出我在程序中更改的内容以找出产品,而不是数量。
Here is the code to be solved in python:下面是python中要解决的代码:
def findNDigitNumsUtil(n, product, out,index):
# Base case
if (index > n or product < 0):
return
f = ""
# If number becomes N-digit
if (index == n):
# if sum of its digits is equal
# to given sum, print it
if(product == 0):
out[index] = "\0"
for i in out:
f = f + i
print(f, end = " ")
return
# Traverse through every digit. Note
# that here we're considering leading
# 0's as digits
for i in range(10):
# append current digit to number
out[index] = chr(i + ord('0'))
# recurse for next digit with reduced sum
findNDigitNumsUtil(n, product - i,
out, index + 1)
# This is mainly a wrapper over findNDigitNumsUtil.
# It explicitly handles leading digit
def findNDigitNums( n, sum):
# output array to store N-digit numbers
out = [False] * (n + 1)
# fill 1st position by every digit
# from 1 to 9 and calls findNDigitNumsUtil()
# for remaining positions
for i in range(1, 10):
out[0] = chr(i + ord('0'))
findNDigitNumsUtil(n, sum - i, out, 1)
# Driver Code
if __name__ == "__main__":
n = 3
sum = 9
findNDigitNums(n, sum)
# This code is contributed
# by ChitraNayal
Disclaimer: this code was written by Github Copilot with minimal supervision.免责声明:此代码由 Github Copilot 在最少监督下编写。
# Display 3-digit prime numbers that have the product of digits equal to a given p-value.
# Example: For p = 9 the numbers 191, 313, 331, 911 meet the conditions of the problem.
def is_prime(n):
if n == 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
def print_3_digit_primes(p):
for i in range(100, 1000):
if is_prime(i) and (i % 10) * (i // 100) * (i % 100 // 10) == p:
print(i)
print_3_digit_primes(9)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.