10. februar 2010

$fato; Prime factorization snippet

/*
$fato(N,[chr]).[k]
returns the prime factorization of a number N, the chr is the ASCII value of the character that will separate the factors , if omitted the value used will be 32 (space). The k property indicates to whether or not use the power notation as shown in the examples below

$fato(36) : 2 2 3 3
$fato(50,44) : 2,5,5
$fato(8).k : 2^3
$fato(36,44).k : 2^2,3^2
*/


alias fato {
var %f,%i 2,%x $1
while (%x && %i <= %x) {

if (%i // %x) {
%f = %f %i
%x = %x / %i
}
else inc %i
}
if ($prop) %f = $regsubex(%f,/((\S+)( \2)*)/g,\2 $+ $iif($numtok(\1,32) > 1, ^ $+ $v1 ))
if ($2) %f = $replace(%f,$chr(32),$chr($2))
return %f
}

Ingen kommentarer:

Send en kommentar