Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Golf: Factorials

by srawls (Friar)
on May 23, 2001 at 04:59 UTC ( #82440=perlmeditation: print w/replies, xml ) Need Help??

This is geared more towards the beginner, to give him a chance to golf, but if you are more advanced and still want to post, than you can just post your code in a 'black box'.

The problem: Passed to your function is a list of numbers, and the function should return a list of those number's factorials. (factorial of 5 is 5*4*3*2*1).


@a = factorial(5); $a[0] = 120<br> @a = factorial(5,3,10); $a[0..2] = (120,6,3628800)

Again, this is meant for beggining to intermidately skilled programmers, but if you are better than that, you can see if you can beat my humble (and probably futile) atempt at the golf. (Click readmore to see my code).

sub f { push@a,eval join'*',1..$_ for@_;@a }

The 15 year old, freshman programmer,
Stephen Rawls

Replies are listed 'Best First'.
Re: Golf: Factorials
by japhy (Canon) on May 23, 2001 at 05:43 UTC
Re: Golf: Factorials
by mr.nick (Chaplain) on May 23, 2001 at 06:17 UTC
    I don't know ... am I a beginner? :) I guess at golf, I am.
    sub f{map{eval join"*",1..$_}@_;}
    33 chars. Duh! Identical as someone else's answer ...
      32 characters if you delete that last ';'...
      sub f{map{eval join"*",1..$_}@_}

      Update: Sorry it's the same as japhy... nothing new.

      BobiOne KenoBi ;)

Re: Golf: Factorials -- 33 but i like it -- (0!=1) or i got 30
by Discipulus (Prior) on Dec 14, 2015 at 12:20 UTC

    sub fact{ (map{$_[0]*=$_}1..$_[0]-1)[-1]||1 # 33 # only 30 char for numbers bigger than 1 # (map{$_[0]*=$_}1..$_[0]-1)[-1] }

    PS some solutions above fails with the number zero that must return 1

    PPS in addition, negatives numbers must return undef or Error
    perl -e "sub fact{$x=$_;$x<0?'E':(map{$x*=$_}1..$x-1)[-1]||1} print ma +p{fact($_),qq(\n)}@ARGV " 0 1 3 -1 1 1 6 E
    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Re: Golf: Factorials
by Anonymous Monk on Apr 10, 2015 at 21:36 UTC
    31 characters
    $a=1;print$a*=$b+=1,$/for 0..10
      Easy to make it 30 with
      $a=1;print$a*=$b+=1,$/for a..k
      لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlmeditation [id://82440]
Approved by root
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (1)
As of 2017-03-24 02:27 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (295 votes). Check out past polls.