2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?
Powershell Solution:
This can be done manually (pen/paper) using prime factorization.
However, since I love powershell… We’ll use it with prime factorization in mind…
- function Get-Factors($number)
- {
- [Array]$result = {1}
- $factor = 2
- while($number -gt 1)
- {
- if($number%$factor -eq 0)
- {
- $result += $factor
- $number /= $factor
- }
- else
- {
- $factor += 1
- }
- }
- return $result
- }
- function Get-NextMultiple($currentMultiple, $currentFactor)
- {
- foreach($factor in Get-Factors($currentFactor))
- {
- $currentMultiple = $currentMultiple * $factor.ToString()
- if($currentMultiple%$currentFactor -eq 0)
- {
- return $currentMultiple
- }
- }
- }
- $currentMultiple = 1
- 1..20|foreach{($currentMultiple = Get-NextMultiple $currentMultiple $_)}|measure -max|%{$_.Maximum}
Note: The solution may not be the optimized one… just a quick hack… I’ll revisit later for optimization if time permits… :-)
No comments:
Post a Comment