算法,发现第一个三角形数与> 500的因素正在运行缓慢角形、第一个、算法、缓慢

2023-09-11 06:59:19 作者:自认与酒同醉

这是我的算法,发现与系列> X因素,第一个三角形数。我可以运行它高达大约x = 150,之后,它永远。我可以做什么样的变化,以加快步伐?谢谢!

 高清triangle_numbers_max_divisors(X)
    triangle_numbers = []
    除数= 0
    一个= 1; B = 2

    直到除数> x
        除数= 0
        triangle_numbers.push(一)
        一个= A + B; B + 1 =

        因为我在1..triangle_numbers.last
            如果triangle_numbers.last%我== 0
                除数+ = 1
            结束
        结束
    结束
    triangle_numbers.last
结束
 

解决方案 阿里凑单算法首次公开 打包购商品挖掘系统解析

您code运行缓慢的原因在其他的答案已经给出。这里是一个Ruby样的方式来$ C C算法$。大概花了大约10秒钟来解决。*

code

 高清triangle_numbers_max_divisors(min_nbr_factors)
  (1..Float ::无穷大)。降低(0)办| tnbr,N |
    tnbr + = N
    如果返回tnbr nbr_factors(tnbr)> = min_nbr_factors
    tnbr
  结束
结束

高清nbr_factors(N)
  M =的Math.sqrt(N)
  2 * 1.upto(M).Count之间{| I | (N%I).zero? }  - ((正== m * m的)1:0)
结束

p triangle_numbers_max_divisors(500)#=> 76_576_500
 

说明

您只需要一个单一的值,所以没有必要继续除数。仅仅指望他们。 如果 N 是一个完美的正方形,术语 - ((N = = M * M)?1:0 引起 N 的平方根为只计算一次。 有时你会看到(1..Float :: INFINITY)写成(1..1.0 / 0)

。 *在最近的一个复古的MacBook Pro

This is my algorithm that finds the first triangle number with > x factors. I can run it up to about x = 150, and after that it takes forever. What changes can I make to speed it up? Thanks!

def triangle_numbers_max_divisors(x)
    triangle_numbers = []
    divisors = 0
    a = 1; b = 2

    until divisors > x
        divisors = 0
        triangle_numbers.push(a)
        a = a + b; b += 1

        for i in 1..triangle_numbers.last
            if triangle_numbers.last % i == 0
                divisors += 1
            end
        end
    end
    triangle_numbers.last
end

解决方案

The reasons your code is running slowly have been given in other answers. Here is a Ruby-like way to code the algorithm. It took about about 10 seconds to solve.*

Code

def triangle_numbers_max_divisors(min_nbr_factors)
  (1..Float::INFINITY).reduce(0) do |tnbr, n|
    tnbr += n
    return tnbr if nbr_factors(tnbr) >= min_nbr_factors
    tnbr
  end
end

def nbr_factors(n)
  m = Math.sqrt(n)
  2 * 1.upto(m).count { |i| (n % i).zero? } - ((n == m * m) ? 1 : 0)
end   

p triangle_numbers_max_divisors(500) #=> 76_576_500

Explanation

You only want a single value, so there is no need to keep divisors. Just count them. If n is a perfect square, the term - ((n == m * m) ? 1 : 0 causes n's square root to be counted only once. Sometimes you will see (1..Float::INFINITY) written as (1..1.0/0).

. * On a recent-vintage Macbook Pro

 
精彩推荐