Division and Sum Digits

excerpt: This covers the basic building blocks such as reduction and counter. tags: input-value-reduction-by-subtraction counter modulo-operator integer-division input-value-reduction-by-division chop-rightmost-digit

Implement a method to perform integer division, it must divide two given numbers.

Division

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def division(a, b)
  count = 0
  
  while a >= b
    a -= b
    count += 1
  end
  
  count
end

p division(3, 2)

The key insight to solve this problem is that division is repeated subtraction.

Building Blocks

  • Reduce Input Value by Subtraction
  • Counter

Sum Digits

Write a method to sum the digits in a number.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def sum(n)
  result = 0
  
  while n != 0
    digit = n % 10 
    result += digit
    n = n / 10
  end
  
  result
end

p sum(1234)

Extract rightmost digit using integer division. The value is reduced by chopping off the rightmost digit.

Building Blocks

  • Modulus
  • Integer Division
  • Reduce Input Value by Division