Ruby beginner - need help optimizing this code

Currently in the process of learning Ruby / programming in general, and I came across this question:

Your task is to build a building that will be a bunch of n cubes. The cube below will have volume n^3, the cube above will have volume (n-1)^3and so on to the top, which will have volume 1^3. You are given the total volume of the mbuilding. Having received m, can you find the number of ncubes that you will need to build? The parameter of the function findNb(find_nb, find-nb)will be an integer m, and you need to return an integer n, for example n^3 + (n-1)^3 + ... + 1^3 = m, if one nexists or -1if there is n*none.

and here is my attempt to solve this:

def find_nb(m)
  (1..Float::INFINITY).each do |n|
    if (1..n).inject(0) {|sum, value| sum + value**3} == m
      return p n 
    else
      next
    end
  end
end

, , , , , , :

find_nb(4183059834009)
find_nb(135440716410000)
find_nb(40539911473216)

:

  • , , n, , , -1 ,

    find_nb(24723578342962)
    
  • , .

+4
2

1: : n , m, .

2: n, - return.

3: next , each.

4: . , .

...

def find_nb(m)
  n = 1
  sum = 1
  while sum < m
    n += 1
    sum += n**3
  end
  return sum == m ? n : -1
end

: , , while (, , ):

def find_nb(m)
  sum = 0
  sizes = 1.upto(Float::INFINITY)
    .lazy
    .map { |n| sum += n ** 3 }
    .take_while { |x| x <= m }
    .to_a
  sizes.last == m ? sizes.length : -1
end
+7

/

, if-statement, , -1. next each ( @Amadan ).

, . . . , total:

def find_nb m
  (1..Float::INFINITY).each do |n|
    total = (1..n).inject(0) { |sum, value| sum + value**3 }
    if total == m
      return n 
    elsif total > m
      return -1
    end
  end
end

find_nb 4183059834009   #=> 2022
find_nb 135440716410000 #=> 4824
find_nb 40539911473216  #=> 3568
find_nb 37              #=> -1

, Ruby loop. with_index :

def find_nb m
  loop.with_index(1) do |_,n|
    t = (1..n).inject { |sum,i| sum + i**3 }
    if t == m
      return n            
    elsif t > m
      return -1        
    end
  end
end

find_nb 4183059834009   #=> 2022
find_nb 135440716410000 #=> 4824
find_nb 40539911473216  #=> 3568
find_nb 37              #=> -1
+1

Source: https://habr.com/ru/post/1662213/


All Articles