As I found no prime factorizer written in Elm, I wanted to do it by myself.
I found first a code in c++ . It works except for bigger numbers, e.g. 84894624407
It fails with segmentation fault (Apple clang version 15.0.0):
MacBook-Pro cplus % ./numberfactors
Give a composite number: 84894624407
zsh: segmentation fault ./numberfactors
So I translated it manually to JavaScript and then it can handle bigger numbers too.
Next I changed it manually to Elm code (look at the LOGS in Ellie.) and it works with the bigger numbers. However, there is another problem: I can get the prime factors as calculated within the recursive function, only through Debug.log in the browser console window.
Is there any way, how to get out the results calculated recursively, to be shown as normal html text instead of console and without using Debug.log or Debug.toString?
For showFactors instead of returning number you could change your accumulator to be a record with fields for each of the values you want to return. The when it completes you can take and convert each of the values to a Strong and print them
Thank you for a good idea!
I wondered, could it be still simpler in the following way:
module Main exposing (main)
import Html exposing (..)
showFactors number factor acc =
if (number < 2) then acc -- returns the final result if number < 2
else
if (modBy factor number == 0) -- modulo used to get prime factors
then let
v2 = acc ++ String.fromInt factor ++ " "
number2 = number // factor
in
showFactors number2 factor v2 -- recursive call
-- this modulus function is used
-- in order to output factor !=2
else
let factor2 = factor + 1
in
showFactors number factor2 acc
-- Driver program to test above function
compositeNr = 84894624407
accumulator = ""
ts = showFactors compositeNr 2 accumulator
main =
text ("Test result " ++ ts)
-- result = 3067 4357 6353
Yes, it works!
There is now nothing left in the log, only this simple text result visible within html, just enough for me:
Test result 3067 4357 6353
Having the numbers as a record instead of a single string may be used to verify the correct result: