Monday, July 2, 2012

Euler Problem 12

I skipped a number of Euler problems since my last post. Anyway, here’s my powershell solution to Problem 12.

http://projecteuler.net/problem=12

It’s not that elegant but it solved the problem in less than 4mins :-)

  1. function Count-Divisors($num) 
  2. { 
  3.     $totalDivisors = 2 
  4.     $subTotal = 0 
  5.     $localDivisor = 2 
  6.     $localNum = $num 
  7.      
  8.     while($localNum -gt 1) 
  9.     { 
  10.         if(($localNum%$localDivisor) -eq 0) 
  11.         { 
  12.             $subTotal++ 
  13.             $localNum/=$localDivisor 
  14.         } 
  15.         else 
  16.         { 
  17.             if($subTotal -gt 0) 
  18.             { 
  19.                 $totalDivisors*=($subTotal+1) 
  20.                 $subTotal = 0 
  21.             } 
  22.             $localDivisor++ 
  23.         } 
  24.     } 
  25.      
  26.     return $totalDivisors 
  27. } 
  28.  
  29. function Get-FTNumber($start, $divisors) 
  30. { 
  31.     $i=$start 
  32.     while ((Count-Divisors ($i * ($i+1)/2)) -le $divisors) 
  33.     { 
  34.         $i++ 
  35.     } 
  36.      
  37.     return ($i * ($i+1)/2) 
  38. } 
  39.  
  40. echo (Get-FTNumber 2 500)