1
\$\begingroup\$

I am a Windows power user, a system tweaker, my idol is Leanardo da Vinci, and now I want to be a hacker. I am extremely new to programming, but I really am a fast learner if I am interested in the subject, now I use PowerShell to hone my programming skills, I have only started learning PowerShell less than a month ago, and here is a script I have written without help dozen days ago to find lcm to test my skill.

This function accepts a string of numbers seperated by comma ",", finds the lcm of the series of numbers and returns it, I have confirmed it is working on PowerShell 7.1 x64 on Windows 10, I want to know if it can be shortened and still maintain human readability and clarity, without changing its logic, feel free to answer if you can help me improve it.

The Script:

Function Find-LCM {
PARAM (
[Parameter(ValueFromPipeline=$true)]
[System.String]$String,
[System.Double]$Number
)
$array=@()
[System.Double]$product=1
$Numbers = $String.Split(",")
foreach ($Number in $Numbers) {
    $sqrt=[math]::sqrt($number)
    $Factor=2
    $count=0
    while ( ($Number % $Factor) -eq 0) {
        $count+=1
        $Number=$Number/$Factor
        if (($array | Where-Object {$_ -eq $Factor}).count -lt $count) {
            $array+=$Factor
        }
    }
    $count=0
    $Factor=3
    while ($Factor -le $sqrt) {
        while ( ($Number % $Factor) -eq 0) {
            $count+=1
            $Number=$Number/$Factor
            if (($array | Where-Object {$_ -eq $Factor}).count -lt $count) {
                $array+=$Factor
                }
            }           
        $Factor+=2
        $count=0
    }
    if ($array -notcontains $Number) {
        $array+=$Number
    }
}
foreach($arra in $array) {$product = $product * $arra}
$product
}

Edit: deleted $maxfactor=[math]::sqrt($number) line and revised prime factorization loop condition to while ($factor -le $number), I did so because when using square root as max factor to factorise 1920 it outputed 15 as a prime factor which is wrong, now it's fixed.

ReEdit: reimplemented square root as prime factorise while loop condition

\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.