CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: PowerShell

Project Euler #1

231 Views
Copy Code Show/Hide Line Numbers
   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
by Please enter a name...
  September 04, 2009 @ 7:02pm
Tags:

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate