How to resolve the algorithm Factors of an integer step by step in the Elixir programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Factors of an integer step by step in the Elixir programming language

Table of Contents

Problem Statement

Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Factors of an integer step by step in the Elixir programming language

Source code in the elixir programming language

defmodule RC do
  def factor(1), do: [1]
  def factor(n) do
    (for i <- 1..div(n,2), rem(n,i)==0, do: i) ++ [n]
  end
  
  # Recursive (faster version);
  def divisor(n), do: divisor(n, 1, []) |> Enum.sort
  
  defp divisor(n, i, factors) when n < i*i    , do: factors
  defp divisor(n, i, factors) when n == i*i   , do: [i | factors]
  defp divisor(n, i, factors) when rem(n,i)==0, do: divisor(n, i+1, [i, div(n,i) | factors])
  defp divisor(n, i, factors)                 , do: divisor(n, i+1, factors)
end

Enum.each([45, 53, 60, 64], fn n ->
  IO.puts "#{n}: #{inspect RC.factor(n)}"
end)

IO.puts "\nRange: #{inspect range = 1..10000}"
funs = [ factor:  &RC.factor/1,
         divisor: &RC.divisor/1 ]
Enum.each(funs, fn {name, fun} ->
  {time, value} = :timer.tc(fn -> Enum.count(range, &length(fun.(&1))==2) end)
  IO.puts "#{name}\t prime count : #{value},\t#{time/1000000} sec"
end)


  

You may also check:How to resolve the algorithm Least common multiple step by step in the REXX programming language
You may also check:How to resolve the algorithm Literals/String step by step in the WEB programming language
You may also check:How to resolve the algorithm Catalan numbers step by step in the Swift programming language
You may also check:How to resolve the algorithm Short-circuit evaluation step by step in the Pike programming language
You may also check:How to resolve the algorithm Wordiff step by step in the Nim programming language