Language: PowerShell
Project Euler #1
1: # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. 2: # Find the sum of all the multiples of 3 or 5 below 1000. 3: 4: $target = 999 5: 6: #first solution (easy) 7: $vals=1..$target 8: $ansA = 0 9: foreach($v in $vals) { 10: if($v % 3 -eq 0 -or $v % 5 -eq 0) { 11: $ansA += $v 12: } 13: } 14: $ansA 15: 16: #second solution (awesome) 17: function sumDivisibleBy { 18: param ( $target, $div ) 19: $times = [System.Math]::Floor( $target / $div ) #the number of full times that the $div fits into $target 20: return ( ( $div * ( $times * ( $times + 1 ) ) ) / 2 ) 21: } 22: 23: $ansB = (sumDivisibleBy 999 3) + (sumDivisibleBy $target 5) - (sumDivisibleBy $target 15) 24: $ansB 25: 26: $ansA -eq $ansB
Tags:
Report Abuse
Subscribe
Discuss
What's new
What is it
New Snippet
Recent Snippets
My Snippets
Web Code
Search

