Author Topic: Factorial competition ..  (Read 680 times)

0 Members and 1 Guest are viewing this topic.

Offline Mad Penguin

  • #Mad_Penguin_UK
  • Administrator
  • Hero Member
  • *****
  • Posts: 1318
  • Karma: 10017
  • Gender: Male
    • View Profile
    • Linux in the UK
    • Awards
Factorial competition ..
« on: July 30, 2013, 04:40:01 pm »
For anyone that's bored, what's the most concise code you can come up with to print out factorial(n) for n in the range 1-11 , in your language of choice?
- If there are any bored Perl programmers about I'm expecting Perl to win .. here's my best attempt in "C" ... be interesting to see how different languages compare [?!]

Code: [Select]
#include <stdio.h>

long factorial(long n) { return n==1?n:n*factorial(n-1); }

int main() { for(int i=1;i<12;i++) printf("Factorial %d = %ld\n",i,factorial(i)); }

Offline Mad Penguin

  • #Mad_Penguin_UK
  • Administrator
  • Hero Member
  • *****
  • Posts: 1318
  • Karma: 10017
  • Gender: Male
    • View Profile
    • Linux in the UK
    • Awards
Re: Factorial competition ..
« Reply #1 on: July 31, 2013, 03:39:19 pm »
Ok, here's the Python submission;

Code: [Select]
def factorial(n):return reduce(lambda x,y:x*y,[1]+range(1,n+1))
Fractionally longer and IMHO a lot less readable [?]

Offline Mad Penguin

  • #Mad_Penguin_UK
  • Administrator
  • Hero Member
  • *****
  • Posts: 1318
  • Karma: 10017
  • Gender: Male
    • View Profile
    • Linux in the UK
    • Awards
Re: Factorial competition ..
« Reply #2 on: August 01, 2013, 02:47:36 am »
Anybody for LISP ?

Code: [Select]
(defun factorial (n)  (if (= n 0) 1 (* n (factorial (- n 1))) ) )

 


SimplePortal 2.3.3 © 2008-2010, SimplePortal