PowerShell Script to Find HCF of Two Numbers
while ($b -ne 0) { $temp = $b; $b = $a % $b; $a = $temp } to find the HCF of two numbers stored in variables $a and $b.Examples
How to Think About It
Algorithm
Code
$a = 48 $b = 18 while ($b -ne 0) { $temp = $b $b = $a % $b $a = $temp } Write-Output "HCF is $a"
Dry Run
Let's trace the example where a=48 and b=18 through the code
Initial values
a=48, b=18
First iteration
temp=18; b=48 % 18 = 12; a=18
Second iteration
temp=12; b=18 % 12 = 6; a=12
Third iteration
temp=6; b=12 % 6 = 0; a=6
| a | b | temp | b after modulo |
|---|---|---|---|
| 48 | 18 | 18 | 12 |
| 18 | 12 | 12 | 6 |
| 12 | 6 | 6 | 0 |
Why This Works
Step 1: Why use the remainder
The remainder operation % helps reduce the problem size by replacing the larger number with the remainder when divided by the smaller number.
Step 2: Loop until remainder is zero
We keep updating the numbers until the remainder becomes zero, which means the last non-zero number is the HCF.
Step 3: Final result
When the loop ends, the variable $a holds the highest common factor of the original two numbers.
Alternative Approaches
function Get-HCF($a, $b) { if ($b -eq 0) { return $a } else { return Get-HCF $b ($a % $b) } } $a = 48 $b = 18 Write-Output "HCF is $(Get-HCF $a $b)"
$a = 48 $b = 18 Add-Type -AssemblyName System.Numerics $hcf = [System.Numerics.BigInteger]::GreatestCommonDivisor($a, $b) Write-Output "HCF is $hcf"
Complexity: O(log(min(a,b))) time, O(1) space
Time Complexity
The Euclidean algorithm runs in logarithmic time relative to the smaller input number because each step reduces the problem size significantly.
Space Complexity
The algorithm uses constant extra space, only a few variables to store numbers and temporary values.
Which Approach is Fastest?
The iterative Euclidean algorithm is generally fastest and simplest; recursion adds overhead, and using .NET methods adds dependency but can be convenient.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative Euclidean | O(log(min(a,b))) | O(1) | Simple and efficient for all cases |
| Recursive Euclidean | O(log(min(a,b))) | O(log(min(a,b))) | Cleaner code but uses call stack |
| .NET Built-in | O(log(min(a,b))) | O(1) | Quick use if .NET knowledge is available |