Project Euler : Problem 003

Project Euler problems in Oforth . Feel free to post your own code.

Project Euler : Problem 003

Postby Franck » 26 Jul 2015 10:45

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

Code: Select all
// Could be simpler (no list creation), but here #factors returns the list of prime factors of an integer.
// This function could be used for other purposes where the entire list is needed.
// So just returns the last element of this list

: factors(n)   // ( n -- aList )
| k p |
   ListBuffer new
   2 ->k
   n sqrt asInteger ->p
   while(k p <=) [
      n k /mod swap 0 &= ifTrue: [
         dup ->n sqrt asInteger ->p
         k over add continue
         ]
      drop k 1+ ->k
      ]
   n 1 > ifTrue: [ n over add ]
   dup freeze ;

// pe003   ( -- n )
: pe003  600851475143 factors last ;
Franck
 
Posts: 159
Joined: 29 Oct 2014 19:01

Return to Project Euler in Oforth

Who is online

Users browsing this forum: No registered users and 1 guest