SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Wizard lukeurtnowski's Avatar
    Join Date
    Mar 2003
    Location
    Coronado
    Posts
    1,644
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)

    dont uderstand this?

    this little snippet of code is hard for me to decipher,
    Code:
    def prime_factors(n)
    return [] if n == 1
    factor = (2..n).find {|x| n % x == 0}
    [factor] + prime_factors(n / factor)
    end
    puts prime_factors(600851475143).max
    Can you explain it?
    why do we return a blank array if n == 1?>
    "Oh, and Jenkins--apparently your mother died this morning."

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    Quote Originally Posted by lukeurtnowski View Post
    why do we return a blank array if n == 1?
    Because it is a recursive function, i.e. a function which calls itself.
    n==1 is a "break condition" which serves to stop the function calling itself for ever (or until the stack size is exceeded).


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •