Rosetta Code

Aliquot sequence classifications

Build short aliquot sequences and classify whether they terminate, loop, or are perfect.

Medium View source
Source rosettacode/popular/aliquot_sequence_classifications.vibe
# title: Aliquot sequence classifications
# source: https://rosettacode.org/wiki/Aliquot_sequence_classifications
# category: Rosetta Code
# difficulty: Medium
# summary: Build short aliquot sequences and classify whether they terminate, loop, or are perfect.
# tags: popular, math, sequences, divisors
# vibe: 0.2

def proper_divisor_sum(number)
  if number == 1
    return 0
  end

  total = 1
  factor = 2

  while factor * factor <= number
    if number % factor == 0
      total = total + factor
      other = number / factor
      if other != factor
        total = total + other
      end
    end
    factor = factor + 1
  end

  total
end

def aliquot_sequence(start_value, limit)
  values = []
  seen = {}
  current = start_value

  while values.length < limit && !seen.fetch("" + current, false)
    values = values.push(current)
    seen["" + current] = true
    current = proper_divisor_sum(current)
  end

  values = values.push(current)
  values
end

def classification(sequence)
  last_value = sequence[sequence.length - 1]
  first_value = sequence[0]

  if last_value == 0
    "terminating"
  elsif last_value == first_value
    "perfect"
  else
    "looping"
  end
end

def run
  values = [6, 10, 12]
  rows = []
  index = 0

  while index < values.length
    sequence = aliquot_sequence(values[index], 8)
    rows = rows.push({
      start: values[index],
      classification: classification(sequence),
      sequence: sequence
    })
    index = index + 1
  end

  rows
end
Output
Press run to execute run from this example.
rosetta-code popular math sequences divisors browser-runner