PowerShell Script to Find Largest of Three Numbers
if ($a -ge $b -and $a -ge $c) { $a } elseif ($b -ge $a -and $b -ge $c) { $b } else { $c } to find the largest of three numbers stored in variables $a, $b, and $c.Examples
How to Think About It
-ge (greater or equal) operator. If it is greater or equal to both, it is the largest. Otherwise, compare the second number similarly. If neither the first nor second is largest, the third must be the largest.Algorithm
Code
$a = 5 $b = 3 $c = 9 if ($a -ge $b -and $a -ge $c) { Write-Output $a } elseif ($b -ge $a -and $b -ge $c) { Write-Output $b } else { Write-Output $c }
Dry Run
Let's trace the example where a=5, b=3, c=9 through the code
Compare a with b and c
Check if 5 >= 3 and 5 >= 9 → false because 5 is not >= 9
Compare b with a and c
Check if 3 >= 5 and 3 >= 9 → false because 3 is not >= 5 or 9
Return c as largest
Since previous checks failed, output 9
| Step | Condition | Result |
|---|---|---|
| 1 | 5 >= 3 and 5 >= 9 | False |
| 2 | 3 >= 5 and 3 >= 9 | False |
| 3 | Return 9 | 9 |
Why This Works
Step 1: Compare first number
The code uses -ge to check if the first number is greater or equal to the other two, ensuring it is the largest if true.
Step 2: Compare second number
If the first number is not largest, the second number is checked similarly to find if it is the largest.
Step 3: Default to third number
If neither first nor second is largest, the third number is returned as the largest by default.
Alternative Approaches
$a = 5 $b = 3 $c = 9 $max = [Math]::Max($a, [Math]::Max($b, $c)) Write-Output $max
$numbers = @(5, 3, 9) $largest = $numbers | Sort-Object -Descending | Select-Object -First 1 Write-Output $largest
Complexity: O(1) time, O(1) space
Time Complexity
The script performs a fixed number of comparisons (at most two), so it runs in constant time O(1).
Space Complexity
Only a few variables are used to store inputs and results, so space complexity is O(1).
Which Approach is Fastest?
Direct comparisons are fastest for three numbers. Using [Math]::Max is also efficient and concise. Sorting is slower and better for larger lists.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct comparisons | O(1) | O(1) | Small fixed number of inputs |
| [Math]::Max method | O(1) | O(1) | Concise code for few inputs |
| Sort-Object array | O(n log n) | O(n) | Finding max in larger lists |