Thursday, September 10, 2009

Euler Problem 3

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?

Quick Powershell Solution:

  1. $num = 600851475143  
  2. $max_prime = 1 
  3.  
  4. $end1 = 0 
  5. while($end1 -eq 0) 
  6. { 
  7.     $factor = 2 
  8.     $end2 = 0 
  9.     while($end2 -eq 0) 
  10.     { 
  11.         if($num%$factor -eq 0) 
  12.         { 
  13.             if($max_prime -lt $factor) 
  14.             { 
  15.                 $max_prime = $factor 
  16.             } 
  17.              
  18.             $num = $num/$factor 
  19.             $end2 = 1 
  20.         } 
  21.         $factor = $factor+1 
  22.     } 
  23.      
  24.     if($num -eq 1) 
  25.     { 
  26.         $end1 = 1 
  27.     } 
  28. } 
  29.  
  30. echo $max_prime 

Note: The solution may not be the optimized one… just a quick hack… I’ll revisit later for optimization if time permits… :-)

No comments: