algorithm - 确定有序素数对 (p, q) 的数量,使得 N = p^2+q^3 使得从 0 到 9 的每个数字都恰好出现一次

标签 algorithm math primes combinatorics sieve-of-eratosthenes

我必须编写一个程序,可以确定素数(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/

相关文章:

prolog - 在 Prolog 中查找素因数

c++ - 应用于数组时呈现数组积分的最小正乘数

algorithm - Theta 表示法和最坏情况运行时间嵌套循环

c++ - 四元数 - 旋转到

c++ - 应用于单个时间序列的独立成分分析

c - math.h 默认舍入模式不明确

c++ - 质数显示和计数c++

python - 为什么我的程序重复打印列表?

algorithm - 如何在没有蛮力方法的情况下有效地组合不相交的集合?

algorithm - 素数计数函数和连续素数的乘积能用多项式时间计算吗?