How to resolve the algorithm Prime decomposition step by step in the Modula-2 programming language
How to resolve the algorithm Prime decomposition step by step in the Modula-2 programming language
Table of Contents
Problem Statement
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number.
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1. If your language does not have an isPrime-like function available, you may assume that you have a function which determines whether a number is prime (note its name before your code). If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes. Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Prime decomposition step by step in the Modula-2 programming language
Source code in the modula-2 programming language
MODULE PrimeDecomposition;
FROM STextIO IMPORT
SkipLine, WriteLn, WriteString;
FROM SWholeIO IMPORT
ReadCard, WriteInt;
CONST
MaxFacIndex = 31;
(* 2^31 has most prime factors (31 twos) than other 32-bit unsigned integer. *)
TYPE
TFacs = ARRAY [0 .. MaxFacIndex] OF CARDINAL;
VAR
Facs: TFacs;
I, N, FacsCnt: CARDINAL;
PROCEDURE CalcFacs(N: CARDINAL; VAR Facs: TFacs; VAR FacsCnt: CARDINAL);
VAR
I: CARDINAL;
BEGIN
FacsCnt := 0;
IF N >= 2 THEN
I := 2;
WHILE I * I <= N DO
IF N MOD I = 0 THEN
N := N DIV I;
Facs[FacsCnt] := I;
FacsCnt := FacsCnt + 1;
I := 2
ELSE
I := I + 1
END
END;
Facs[FacsCnt] := N;
FacsCnt := FacsCnt + 1
END;
END CalcFacs;
BEGIN
WriteString("Enter a number: ");
ReadCard(N);
SkipLine;
CalcFacs(N, Facs, FacsCnt);
(* There is at least one factor *)
IF FacsCnt > 1 THEN
FOR I := 0 TO FacsCnt - 2 DO
WriteInt(Facs[I], 1);
WriteString(" ")
END;
END;
WriteInt(Facs[FacsCnt - 1], 1);
WriteLn
END PrimeDecomposition.
You may also check:How to resolve the algorithm Quickselect algorithm step by step in the NetRexx programming language
You may also check:How to resolve the algorithm Program termination step by step in the Oforth programming language
You may also check:How to resolve the algorithm Hello world/Line printer step by step in the UNIX Shell programming language
You may also check:How to resolve the algorithm Loops/While step by step in the NetRexx programming language
You may also check:How to resolve the algorithm Average loop length step by step in the Unicon programming language