[英]Print all n-digit numbers whose product of digits equals to given product python
在此處輸入圖像描述顯示 3 位素數,這些素數的數字乘積等於給定的 p 值。 示例:對於 p = 9,數字 191、313、331、911 滿足問題的條件。
我找到了一個代碼,它只是為了找出它們的數量而不是產品。 我需要找出我在程序中更改的內容以找出產品,而不是數量。
下面是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
免責聲明:此代碼由 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.