【问题标题】:using while loop the page keep loading over and over (codewars problem)使用while循环页面不断加载(codewars问题)
【发布时间】:2021-10-24 01:04:22
【问题描述】:

嘿,伙计们,我正在尝试解决阶乘分解(代码战任务) 好吧,有些数字对我有用,直到我达到第 23 位,页面不断循环,请有人帮助我

function decomp(n) {
  let c =[]
  let sum =1
 for(let i=n;i>=1;i--){
   sum*=i
 }
 let k= 2
 
 while(k<=sum){
  if(sum%k!==0){
  k++}
  while(sum%k==0){
    c.push(k)
sum = sum/k

} 
 }
  return c.join('*')
}

该函数运行良好,直到我达到数字 23 并一遍又一遍地加载,任务是关于函数 decomp(n) 并且应该返回 n 的分解!以素数的递增顺序将其转换为素数,作为字符串。

阶乘可以是一个非常大的数字(4000!有 12674 位,n 可以从 300 到 4000)。

在 Fortran 中 - 与任何其他语言一样 - 返回的字符串不允许包含任何多余的尾随空格:您可以使用动态分配的字符串。

例子

n = 12; decomp(12) -> "2^10 * 3^5 * 5^2 * 7 * 11"

从 12 岁开始!能被 2 整除 10 次,被 3 整除 5 次,被 5 整除 2 次,被 7 和 11 整除一次。

n = 22; decomp(22) -> "2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19"

n = 25; decomp(25) -> 2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23

【问题讨论】:

    标签: algorithm loops while-loop task loading


    【解决方案1】:

    23!不能用 double-precision floating-point format 精确表达,JavaScript 用它来表示它的数字。

    但是,您不需要计算 n!。您只需要分解每个数字并连接它们的分解。

    实际上,您甚至不需要分解每个数字。请注意,给定np,有不大于n(n/p) 数字是p 的倍数,(n/(p*p))p*p 的倍数等。

    function *primes(n) {
      // Sieve of Eratosthenes 
      const isPrime = Array(n + 1).fill(true);
      isPrime[0] = isPrime[1] = false;
      for (let i = 2; i <= n; i++) {
        if (isPrime[i]) {
          yield i;
          for (let j = i * i; j <= n; j += i)
            isPrime[j] = false;
        }
      }
    }
    
    function decomp(n) {
      let s = n + '! =';
      for (const p of primes(n)) {
        let m = n, c = 0;
        // There are (n/p) numbers no greater than n that are multiples of p
        // There are (n/(p*p)) numbers no greater than n that are multiples of p*p
        // ...
        while (m = ((m / p) | 0)) {
          c += m;
        }
        s += (p == 2 ? ' ' : ' * ') + p + (c == 1 ? '' : '^' + c);
      }  
      return s;
    }
    
    console.log(decomp(12))
    console.log(decomp(22))
    console.log(decomp(23))
    console.log(decomp(24))
    console.log(decomp(25))

    【讨论】:

    • 非常感谢先生,对不起,我对生成器和迭代器不是很熟悉,我不明白在这个例子中我的确切含义是什么,我知道前两个项目都是用 false 和从索引 2 开始是真的
    猜你喜欢
    • 2011-10-22
    • 1970-01-01
    • 2018-12-10
    • 2011-07-21
    • 2020-08-05
    • 2021-01-17
    • 2020-06-13
    • 1970-01-01
    • 2011-06-19
    相关资源
    最近更新 更多