【问题标题】:Trying to find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20试图找到能被 1 到 20 的所有数字整除的最小正数
【发布时间】:2018-05-05 21:13:47
【问题描述】:

我试图找到可以被 1 到 20 的所有数字整除的最小正数。我们得到 2520 是可以被 1 到 10 的每个数字整除的最小数字任何剩余。我的 find() 找到从 2520 开始的数字,该数字可以被 1-20 的所有数字整除,但由于某种原因返回 2520。我找不到我的 find() 有什么问题?

  public class Solution  {

  public ArrayList<Integer> list = new ArrayList<Integer>();


// creating a list of integers from 1 to 20
public ArrayList<Integer> addtolist() {
  for (int i = 1; i <= 20; i++) {
    list.add(i);
  }
  return list;
}

// finds the smallest positive number that is evenly divisible by all 
of the numbers from 1 to 20

public int find() {
  int num = 2520;
  while(true) {
    for(int i: list) {
      if(num % i == 0) {
        return num;
      }
      else {
        num = num + 1;
      }

    }
  }
}

public static void main(String[] args) {
  Solution sol = new Solution();
  sol.addtolist();
  System.out.println(sol.find());//2520
}


}

【问题讨论】:

  • 找出小于或等于 20 的素数,然后找出小于或等于 20 的每个素数的最大幂。将它们相乘。那是16*9*5*7*11*13*17*19=232792560
  • 这被称为最小公倍数 LCM 以防万一你想知道用谷歌搜索什么,Eratosthenes SoESoE

标签: java algorithm math division greatest-common-divisor


【解决方案1】:

你的find 函数返回num,如果any i in list 将它分开。它应该只返回num,如果每个 i in num 是一个除数。

虽然不得不说,这远不是解决问题的最有效方法。

【讨论】:

    【解决方案2】:

    (num % i == 0) 时,您从 for 循环返回,因为 i 从 1 开始,这总是正确的。相反,您需要等到结束才能返回:

    public int find() {
      int num = 2520;
      while(true) {
        boolean allDivisible = true;
        for(int i: list) {
          if(num % i != 0) {
            allDivisible = false;
            break;
          }
        }
        if (allDivisible) {
          return num;
        else {
          num = num + 1;
        }
      }
    }
    

    【讨论】:

      【解决方案3】:

      在您的代码中:

      for(int i: list) {
        if(num % i == 0) {
          return num; // Returns immediately. 
        }
        else {
          num = num + 1;
        }
      }
      

      您在列表中找到匹配的数字后立即返回。您要做的只是在找到与列表中的所有值匹配的值时返回。

      【讨论】:

        【解决方案4】:

        好问题!

        long answer = LongStream.iterate(1, n -> n + 1)
            .filter(n -> IntStream.rangeClosed(1, 20).allMatch(f -> n % f == 0))
            .findFirst().getAsLong();
        

        答案是 232792560

        显然有很多使用数学的捷径(例如,只查看偶数,忽略 1 到 20 中的数字,这些数字是该范围内其他数字的因数)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-12-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-04-30
          • 2018-04-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多