Prime Factorization using recursion in Elm?

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?

1 Like

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 
   if (modBy factor number == 0)   -- modulo used to get prime factors
   then let 
            v2 = acc ++ String.fromInt factor ++ " " 
            number2 = number // factor
            showFactors number2 factor v2  -- recursive call

   -- this modulus function is used
   -- in order to output factor !=2 
     let factor2 = factor + 1 
        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:

factor1 * factor2 * factor3 == number
3067 * 4357 * 6353 =  84894624407
1 Like

The calculated prime factors are saved into a list.
The calculated product of the factors within the list is equal to the original number.

New version with number input field ( + browser.sandbox TEA )

Added to Rosetta Code now !

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.