Advertisement
Guest User

Untitled

a guest
Feb 19th, 2020
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.15 KB | None | 0 0
  1.  
  2. def run(n)
  3.     result = findRuns(getMarchingWidthValues(n).reverse)   
  4.     puts "#{result.inspect}"
  5. end
  6.  
  7.  
  8. def getMarchingWidthValues(n)
  9.     Array.new(n) {|i| [i + 2, biggestFactorSmallerThanSquareRoot(i + 2)]}
  10. end
  11.  
  12.  
  13. def biggestFactorSmallerThanSquareRoot(n)
  14.  
  15.     arr = divisors(n).select{|x| x <= squareRootFloor(n)}
  16.    
  17.     val = arr.pop
  18.  
  19.     if val ** 2 == n
  20.         val = arr.pop
  21.     end
  22.  
  23.     return val
  24. end
  25.  
  26. def findRuns(arr)
  27.     runs = Hash.new
  28.  
  29.     target = 1
  30.  
  31.     currentRun = []
  32.     arr.each_index do |i|
  33.         if target == arr[i][1]
  34.             currentRun.push(arr[i])
  35.             target = target + 1
  36.         else
  37.             runs[currentRun.length] = currentRun
  38.             currentRun = []
  39.             target = 1
  40.         end
  41.     end
  42.  
  43.     return runs
  44. end
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58. def squareRootFloor(n)
  59.     min = 1
  60.     max = n / 2
  61.  
  62.     while (max - min > 1)
  63.         g = (max + min) / 2
  64.  
  65.         if g ** 2 == n
  66.             return g
  67.         end
  68.  
  69.         if g ** 2 > n
  70.             max = g
  71.         else
  72.             min = g
  73.         end
  74.  
  75.     end
  76.  
  77.     return min
  78. end
  79.  
  80. def divisors(n)
  81.     result = []
  82.  
  83.     max = squareRootFloor(n) + 1
  84.     k = 1
  85.  
  86.     while k <= max
  87.         if n % k == 0
  88.             result.push(k)
  89.             result.push(n / k)
  90.         end
  91.         k = k + 1
  92.     end
  93.    
  94.  
  95.     return result.uniq.sort
  96. end
  97.  
  98.  
  99.  
  100.  
  101. run 1000
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement