Language: PowerShell
Project Euler #3
1: #The prime factors of 13195 are 5, 7, 13 and 29. 2: #What is the largest prime factor of the number 600851475143 ? 3: 4: function getPrimes { #sieve of eratosthenes, http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes 5: param ($target) 6: $nums = @(2..$target) 7: $curPrime = 2 8: for ($i = 0; [math]::pow($curPrime, 2) -le $target; $i ++) { 9: if ($nums[$i] -ne -1) { 10: $curPrime = $nums[$i] 11: write-debug "Prime`t`t$curPrime" 12: for ($x = [math]::pow($curPrime, 2); $x -le $target; $x = $x + $curPrime) { 13: $curNum = $nums[$x - 2]; 14: if($curNum -ne -1) { 15: write-debug ("Composite`t{0}" -f $nums[$x - 2]) 16: $nums[$x - 2] = -1 17: } 18: } 19: } 20: } 21: return ($nums | where { $_ -ne -1 }) 22: } 23: 24: function factorPrime { 25: param($target,$primes) 26: foreach($prime in $primes) { 27: do { 28: $r = $target / $prime 29: $c = ($r -eq [long]$r) 30: if ($c) { 31: $prime 32: $target = $r 33: } 34: } 35: while ($c) 36: if ($prime -ge $target) { 37: return 38: } 39: } 40: throw "not enough primes" 41: } 42: 43: $primes = getPrimes 10000 44: factorPrime 600851475143 $primes
Tags:
Report Abuse
Subscribe
Discuss
What's new
What is it
New Snippet
Recent Snippets
My Snippets
Web Code
Search

