Rosetta Code

Prime decomposition

Decompose composite integers into their prime factors with straightforward trial division.

Medium View source
Source rosettacode/popular/prime_decomposition.vibe
# title: Prime decomposition
# source: https://rosettacode.org/wiki/Prime_decomposition
# category: Rosetta Code
# difficulty: Medium
# summary: Decompose composite integers into their prime factors with straightforward trial division.
# tags: popular, math, primes, factors
# vibe: 0.2

def prime_decomposition(number)
  factors = []
  remaining = number

  while remaining % 2 == 0
    factors = factors.push(2)
    remaining = remaining / 2
  end

  candidate = 3
  while candidate * candidate <= remaining
    while remaining % candidate == 0
      factors = factors.push(candidate)
      remaining = remaining / candidate
    end
    candidate = candidate + 2
  end

  if remaining > 1
    factors = factors.push(remaining)
  end

  factors
end

def run
  {
    twelve: prime_decomposition(12),
    thousand_twenty_three_times_thousand_twenty_four: prime_decomposition(1023 * 1024),
    sample_composite: prime_decomposition(2 * 3 * 5 * 7 * 11 * 11 * 13 * 17)
  }
end
Output
Press run to execute run from this example.
rosetta-code popular math primes factors browser-runner