Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Zeckendorf representation

by Athanasius (Monsignor)
on Aug 25, 2012 at 04:30 UTC ( #989689=note: print w/ replies, xml ) Need Help??


in reply to Zeckendorf representation

Hello thmsdrew,

I agree with tye — this is cool! And I’m impressed with the speed at which the calculations are done; this calculation:

zeck(1019377012345) = 956722026041 + 53316291173 + 7778742049 + 113490 +3170 + 267914296 + 102334155 + 39088169 + 14930352 + 514229 + 196418 ++ 46368 + 17711 + 6765 + 987 + 377 + 55 + 21 + 8 + 1

(see code below) takes less than a second on my machine!

My only quibble is with the design of the zeck subroutine. A sub containing exit is a red flag for me, and even print statements are better deferred to the caller. To my mind, zeck should return the sum as a list of Fibonacci numbers. And in Perl, this is surprisingly easy to do:

my @zeck = zeck($ARGV[0]); print 'zeck(', $ARGV[0], ') = ', join(' + ', @zeck), "\n"; sub zeck { return $_[0] if is_fibonnacci($_[0]); my $count = 0; my $prev = 0; my $curr = 0; while (($curr = fibonnacci($count)) < $_[0]) { $prev = $curr; $count++; } return ($prev, zeck($_[0] - $prev)); }

Note that by restricting sub zeck to a single responsibility, the code becomes both more flexible and shorter.

Again, thanks for a cool demo!

P.S. I actually find jwkrahn’s one-line version of sub is_perfect_square to be clearer than the original. I guess clarity is in the eye of the beholder!

Athanasius <°(((><contra mundum


Comment on Re: Zeckendorf representation
Select or Download Code
Re^2: Zeckendorf representation
by thmsdrew (Scribe) on Aug 27, 2012 at 03:41 UTC

    Thank you for that. I see what you mean, and prefer yours. Why do you say that a sub containing exit is a red flag?

      Why do you say that a sub containing exit is a red flag?

      From exit:

      Don't use exit to abort a subroutine if there's any chance that someone might want to trap whatever error happened. Use die instead, which can be trapped by an eval.

      Think of a subroutine as a server providing a service to its clients (callers). It’s up to the client to decide how to handle the information returned by its server. Even an exception (thrown by die) is information which the client can use or ignore as desired. The server should never preempt the client in determining how to proceed.

      Hope that helps,

      Athanasius <°(((><contra mundum

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://989689]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (7)
As of 2014-12-28 15:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (182 votes), past polls