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.     $factor = 2 
  7.     $end2 = 0 
  8.     while($end2 -eq 0) 
  9.     { 
  10.         if($num%$factor -eq 0) 
  11.         { 
  12.             if($max_prime -lt $factor
  13.             { 
  14.                 $max_prime = $factor 
  15.             } 
  16.              
  17.             $num = $num/$factor 
  18.             $end2 = 1 
  19.         } 
  20.         $factor = $factor+1 
  21.     } 
  22.      
  23.     if($num -eq 1) 
  24.     { 
  25.         $end1 = 1 
  26.     } 
  27.  
  28. 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: