我必须编写一个程序,可以确定素数(p,q)的有序对的数量,这样当N = p ^ 2 + q ^ 3写成十进制时,出现从0到9的每个数字恰好一次(没有前导零)。
我想使用埃拉托色尼筛的变体,正如它所解释的 here ,然而,它也提到,筛子仅适用于数字 N,使得 N 小于一千万,但根据问题的陈述,每个 N 至少是一亿,因为每个数字只出现一次并且没有前导零,但除了这个之外我没有任何其他想法,因此我们将不胜感激。
最佳答案
利用这样一个事实:您可以立方并仍然形成潜在有效数字的最大质数是 2143。
Ruby 代码(如果不使用 Ruby,则视为伪代码):
require 'prime'
def f()
# Determine the max & min numbers that can be made with 10 distinct digits and no leading zeroes
max_num = 9_876_543_210
min_num = 1_023_456_789
# Find the largest prime having a cube <= max_num
max_prime_to_cube = 2143
count = 0
# Cube every prime up to 2143
Prime.each do |prime_to_cube|
return count if prime_to_cube > max_prime_to_cube
cubed_val = prime_to_cube ** 3
# Try adding the square of every prime until we exceed the maximum valid number
Prime.each do |prime_to_square|
squared_val = prime_to_square ** 2
combined_val = squared_val + cubed_val
next if combined_val < min_num
break if combined_val > max_num
# Check if all digits are unique
if has_each_digit_once(combined_val)
count += 1
puts "val: #{combined_val} = #{prime_to_square}^2 + #{prime_to_cube}^3, count: #{count}"
end
end
end
end
# Check each digit, setting bits of check_int where the i'th bit represents digit i
def has_each_digit_once(val_to_check)
check_int = 0
10.times do
check_bit = 1 << (val_to_check % 10)
# Exit early if we see a digit for the second time
return false if check_bit & check_int > 0
check_int |= check_bit
val_to_check /= 10
end
return check_int == 1023
end
结果:
> f
val: 1328675409 = 36451^2 + 2^3, count: 1
val: 1478325609 = 38449^2 + 2^3, count: 2
val: 3085469217 = 55547^2 + 2^3, count: 3
val: 3507126849 = 59221^2 + 2^3, count: 4
...
val: 9682357410 = 5689^2 + 2129^3, count: 1267
val: 9837162450 = 13681^2 + 2129^3, count: 1268
val: 9814362750 = 523^2 + 2141^3, count: 1269
val: 9815674302 = 1259^2 + 2141^3, count: 1270
=> 1270
关于algorithm - 确定有序素数对 (p, q) 的数量,使得 N = p^2+q^3 使得从 0 到 9 的每个数字都恰好出现一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76801481/