[英]Given n, find how many n-digit numbers are there such that the number has prime digit at prime indices and is divisible by m?
特殊數字是這樣的數字在素數索引上具有素數(2、3、5、7),在非素數索引上具有非素數。 (例如,15743 - 素數索引 (2, 3, 5) 具有素數 (5, 7, 3))。 有多少個 n 位數的特殊數也能被 m 整除。
例如,對於 n=2 和 m=2,答案將是 [12,42,62,82,92],所以 5。
我寫了一個回溯算法,它找到所有特殊數字的排列,然后檢查這些特殊數字中的每一個是否可以被 m 整除並返回計數。 這適用於 n 和 m 的小值,但問題的 n、m 值在 0-500 的范圍內。
var primes = [2, 3, 5, 7] var nonPrimes = [1, 4, 6, 8, 9] n = 2 // number of digits m = 2 //divisor k = 0 //remainder function rec(index, temp, count) { if (temp.length >= n) { if (Number(temp) % m === k) { /* console.log(temp) */ count += 1 } return count } if (primes.includes(index)) { for (num1 in primes) { temp += primes[num1]; count = rec(index + 1, temp, count) temp = temp.slice(0, -1) } } else if (nonPrimes.includes(index)) { for (num2 in nonPrimes) { temp += nonPrimes[num2]; count = rec(index + 1, temp, count) temp = temp.slice(0, -1) } } return count } console.log("number of n-digit special numbers which are divisible by m with remainder k is ", rec(1, "", 0))
由於逐位遞歸可以使它們相互依賴,因此對小於m
的所有余數求解並返回余數 0 的解。給定一個計數表,其中包含“特殊”數字的計數表,當除以m
時剩余r
到第i
個索引。 然后將索引i + 1
的行制成表格:
(1) Transform the current row of remainders,
each storing a count, multiplying by 10:
for remainder r in row:
new_r = (10 mod m * r) mod m
new_row[new_r] += row[r]
row = new_row
(2) Create new counts by using the new
possible digits:
initialise new_row with zeros
for d in allowed digits for this ith row:
for r in row:
new_r = (r + d) mod m
new_row[new_r] += row[r]
例如, n = 2, m = 2
:
row = [None, None]
# We are aware of the allowed digits
# at the ith row
row[0] = 3 # digits 4, 6 and 8
row[1] = 2 # digits 1, 9
row = [3, 2]
(1) 變換:
new_row = [0, 0]
remainder 0:
new_r = (10 mod 2 * 0) mod 2 = 0
new_row[0] += row[0] = 3
remainder 1:
new_r = (10 mod 2 * 1) mod 2 = 0
new_row[0] += row[1] = 5
row = new_row = [5, 0]
(2) 創建新計數:
new_row = [0, 0]
d = 2:
rd = 2 mod 2 = 0
r = 0:
new_r = (0 + 0) mod 2 = 0
new_row[0] += row[0] = 5
r = 1:
new_r = (1 + 0) mod 2 = 1
new_row[1] += row[1] = 0
d = 3: # Similarly for 5, 7
rd = 3 mod 2 = 1
r = 0:
new_r = (0 + 1) mod 2 = 1
new_row[1] += row[0] = 5
r = 1:
new_r = (1 + 1) mod 2 = 0
new_row[0] += row[1] = 5 # unchanged
row = new_row = [5, 15]
[12,42,62,82,92]
[13,15,17,
43,45,47,
63,65,67,
83,85,87,
93,95,97]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.