Skip to content
loading...

re: Daily Challenge #152 - Strongest Number in an Interval VIEW POST

FULL DISCUSSION
 

Here's a Nim submission!

proc even(i: int): bool {.inline.} = i mod 2 == 0

proc numStrength(i: int): int =
  ## Calculate the strength of a number.
  ##
  ## A number's strength is determined by the number of times
  ## it can divided in half until it reaches an odd number.
  var i = i
  while i.even:
    i = i div 2
    inc(result)

proc strongestNum(n, m: int): int =
  ## Given the closed interval [n, m], calculate the strongest number.
  var topStrength = 0
  for i in n..m:
    let strength = numStrength(i)
    if strength > topStrength:
      topStrength = strength
      result = i

assert strongestNum(1, 2) == 2
assert strongestNum(5, 10) == 8
assert strongestNum(48, 56) == 48
assert strongestNum(129, 193 == 192

There's definitely room to improve this, but I'm just starting to look into Nim's standard library, and I don't know all that's available to me yet.

code of conduct - report abuse