algorithm - 为 n 找到最近的下一个数字,以及 2 个数字的倍数之和

标签 algorithm

对于给定的数字 n,找出下一个最接近的可以由两个给定数字 (a,b) 和 n 的倍数组成的数字之间的差值。

Example:
    n = 49, (a, b) = (13, 17) => Difference = 2
    Nearest number would be = 51 (3*17, 0*13)

    n = 16, (a, b) = (2 , 5) => Difference = 0
    Nearest number would be = 16 (2*5, 3*2)

    n = 25, (a, b) = (13, 17) => Difference = 1
    Nearest number would be = 26 (0*17, 2*13)

我该如何解决这个问题?

我写的是:( ruby )

def find_next_num_diff(x,y,z)
  x, y = x > y ? [x, y] : [y, x]
  while(z%y > 0 && z >= x) do
    z -= x
  end
  if z%y == 0
    return 0
  else
    return [y-(z%y), x-z].min
  end
end

以上代码不适用于最后一种示例。

编辑: 没有负数。而且只有总和。 起初我认为这个问题是求解 X & Y for Equation Xa + Yb >= nX, Y > 0

最佳答案

我会从这样的事情开始:

def find_next_num_diff(n, a, b)
  multiples_of_a = (0..n+a-1).step(a).to_a
  multiples_of_b = (0..n+b-1).step(b).to_a

  multiples_of_a.product(multiples_of_b).map { |x, y| (n - (x + y)).abs }.min
end

find_next_num_diff(49, 13, 17)
#=> 2
find_next_num_diff(16, 2, 5)
#=> 0
find_next_num_diff(25, 13, 17)
#=> 1

或者您可能希望使用以下需要较少内存的实现,因为它不会将笛卡尔积存储在内存中:

def find_next_num_diff(n, a, b)
  a_multiples = (0..n+a-1).step(a)
  b_multiples = (0..n+b-1).step(b)

  smallest = Float::INFINITY

  a_multiples.each do |x|
    b_multiples.each do |y|
      smallest = [smallest, (n - (x + y)).abs].min
    end
  end

  smallest
end

关于algorithm - 为 n 找到最近的下一个数字,以及 2 个数字的倍数之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41621143/

相关文章:

在迷宫中寻找移动实体的算法

java - 与树相关的递归

c# - 如何找到字符串格式错误的 XML(在 C# 中)的位置?

c# - 这是快速排序吗?

algorithm - PredictionIO - 一个引擎和多个算法

c - 获取位掩码以交付给所有设备的快速方法

algorithm - 粒子群优化(PSO)算法中位置向量和速度向量的内容(元素)是什么?

algorithm - 更新范围并跟踪每个索引处出现的最大值

algorithm - 下载剩余时间预测器

php - 如何获得 789 之前所有可能的数字组合?