• (cs) in reply to gdm500ps
    gdm500ps:
    I would also like to point out that, contrary to the story, the candidate claimed to have at least three years of professional experience. Doing what, I have no idea.
    Unfortunately, neither does their previous employer... ;)
  • Danny (unregistered) in reply to Noamsml

    High five, fellow recursing high school student. AP CompSci rules.

    Oh, and by the way, you would get a compile error: unreachable statement return 42; ^

    ;)

  • (cs)

    YOU CALL THAT A FACTORIAL???

    THIS IS A FACTORIAL!! (Java code)

    
    public class Factorial
    {
    	public static int computeFactorial(int n)
    	{
    		if (n > 0)
    		{
    			if (n > 1)
    			{
    				if (isEven(n))
    					return evenFactorial(n);
    				else
    					return oddFactorial(n);
    			}
    			else
    				return baseFactorial();
    		}
    		else
    			return errorFactorial();
    		
    	}
    	
    	private static int evenFactorial(int n)
    	{
    		if (n > 1)
    		{
    			return n * oddFactorial(n-1);
    		}
    		else
    			return n * baseFactorial();
    	}
    	
    	private static int oddFactorial(int n)
    	{
    		if (n > 1)
    		{
    			return n * evenFactorial(n-1);
    		}
    		else
    			return n * baseFactorial();		
    	}
    	
    	private static int baseFactorial()
    	{
    		return 1;
    	}
    	
    	private static boolean isEven(int n)
    	{
    		int i = n/2;
    		if (i*2 == n)
    			return true;
    		else
    			return false;
    	}
    	
    	private static int errorFactorial()
    	{
    		return 42;
    	}
    }
    
    

    Addendum (2007-06-27 21:40): YOU CALL THAT A FACTORIAL???

    THIS IS A FACTORIAL!! (Java code)

    
    public class Factorial
    {
    	public static int computeFactorial(int n)
    	{
    		if (n > 0)
    		{
    			if (n > 1)
    			{
    				if (isEven(n))
    					return evenFactorial(n);
    				else
    					return oddFactorial(n);
    			}
    			else
    				return baseFactorial();
    		}
    		else
    			return errorFactorial();
    		
    	}
    	
    	private static int evenFactorial(int n)
    	{
    		if (n > 1)
    		{
    			return n * oddFactorial(n-1);
    		}
    		else
    			return n * baseFactorial();
    	}
    	
    	private static int oddFactorial(int n)
    	{
    		if (n > 1)
    		{
    			return n * evenFactorial(n-1);
    		}
    		else
    			return n * baseFactorial();		
    	}
    	
    	private static int baseFactorial()
    	{
    		return 1;
    	}
    	
    	private static boolean isEven(int n)
    	{
    		int i = n/2;
    		if (i*2 == n)
    			return true;
    		else
    			return false;
    	}
    	
    	private static int errorFactorial()
    	{
    		return 42;
    	}
    }
    
    

    Look and behold. Adherence to OO principles of encapsulation; front-end interface; error checking; good modulation (base case obviously has to be treated separately from main logic flow); and most importantly, adherence to specifications. The requirement is recursion right? Therefore, we jump back and forth between two different functions, just so the compiler doesn't get all smart and decide to "optimize" my recursive code to iterative.

    Enterprisiness at its best.

    Addendum (2007-06-27 21:42): //todo: Implement this in a 3-tier architecture with a client-server model. This baby's so gonna sell.

  • MH (unregistered)

    Guess you haven't sampled the curriculums (curriculi?) of too many schools..

    When I TA'd/taught EE/CE, we regularly encouraged students to use RCS or CVS for source control..

    MH

  • (cs) in reply to MH
    MH:
    curriculums (curriculi?)
    curricula.
  • Certified Goooooooogler (unregistered)

    a) Search Google for "factorial in c++" b) click on first link (http://www.engin.umd.umich.edu/CIS/course.des/cis400/cpp/factorial.html) c) Copy/Paste or Print code to hand it over to the interviewing dude!

  • sergio (unregistered)

    Amazing grace!.... 5+ pages of comments to factorial calculation, with WTF own solutions! Get a life, folks!

    As much as I hate captchas in comments, this one fits: sanitarium

  • (cs) in reply to Welbog
    Welbog:
    Fj_:
    It actually returns 13, because 12 is incremented one last time before the comparison.
    I suggest learning more about for loops.
    I suggest at least understanding what's wrong when attempting to bash someone.

    His idea of for loops is perfectly right; the problem is the variable a, which is not changed.

  • Nibu (unregistered)

    He was quite frank in saying that he didn't know what the hell is recursion. :)

    Well I can't see 'n' being used anywhere. Anyway he tried. :P

    Thinking about some of my friends here in India. Their were all nice but when it comes to writing programs... :((

    Can't imagine how they are managing right now.

  • Slag (unregistered) in reply to gsmalleus

    Actually, the code should be something like

    int factorial(int n){

     if ( n <= 1 ) return 1
    
     else return n * factorial n-1;
    

    }

  • greg (unregistered)

    Obligatory Whitespace solution:

    // :D

  • (cs) in reply to digislave
    digislave:
    Will:
    ...

    Isn't factorial(0) defined as 1?

    Captcha: muhahaha!

    Yeah, he got the base case wrong. Here's a hint when writing recursive functions: figure out the base case first.

    Ooh captcha == burned, how appropriate

    factorial(0) is 1, and the planet we live on is flat.

    The same ontology applies in both cases. There definitely are recursive algorithms that require a base case. Factorial is not one of them. All you need to define the factorial function meaningfully is to specify a sensible domain, the realm of positive integers. Given that specification, one can simply say that the factorial is the product of all numbers from n down to 1.

    The assertion that the factorial of 0 is 1 is both meaningless in terms of the generation of factorials, and pointless, since you still have to limit the domain of the function to non-negative integers. What's the point in defining a factorial of 0?

  • (cs) in reply to rjnewton
    rjnewton:
    factorial(0) is 1, and the planet we live on is flat.

    The same ontology applies in both cases. There definitely are recursive algorithms that require a base case. Factorial is not one of them. All you need to define the factorial function meaningfully is to specify a sensible domain, the realm of positive integers. Given that specification, one can simply say that the factorial is the product of all numbers from n down to 1.

    The assertion that the factorial of 0 is 1 is both meaningless in terms of the generation of factorials, and pointless, since you still have to limit the domain of the function to non-negative integers. What's the point in defining a factorial of 0?

    Ever heard of binomial coefficient? Pascal's triangle?

    Just two examples that need 0!. As far as I recall, there are functions in probability that also depend on it.

    EDIT: and that coming from rjnewton. How ironic…

  • indigoviolet (unregistered) in reply to American Programmer
    American Programmer:
    Lemme guess, an H1B candidate here because he is "more qualified" (where "qualified" is a function inversely proportional to salary requirements) than any American.

    Seriously, I see that all the time - more from H1Bs, but I also taught CS at a state university and it is not uncommon for students of certain ethnic backgrounds to work as a team when doing assignments. The net result is that 1 student who worked by himself and followed the rules is worth n foreign students working in a team - which is why you have to pay him n times as much. If you want to duplicate his knowledge, you have to hire all n foreign students because they all only know 1/nth as much as the American.

    On a related note - be sure to contact you congressman to oppose the new immigration bill that doubles the number of available H1B visas.

    WTF does any of this have to do with H1Bs?

  • (cs)

    Having been interviewed recently for five hours (three were planned) includig some dry run programming on a white board, I feel some sympathy for the graduate interviewed in this WTF. No, I did not act as stupid as this fellow and I didn't just graduate, but beeing gazed at by some possible future colleague with bushy brows and very very deep dark eyes, simple things like separating words within a sentence become terrible difficult. Especially when using C and forgetting about strtok() and its friends. Therefore doing everything the hard way with loops and unavoidable off-by-one errors takes time and sweat to get at least half-finished.

    After all, it seems as if I did not score too bad since they wanted to send me an offer. On the other hand, I've not ssen it yet...

    And by the way, I had to use source control and bug tracking means within my studies, so I guess my University of Applied Sciences (located in Stralsund, Germany) is not so bad at all.

  • DiRadical (unregistered) in reply to Protiuz

    That's nothing. I asked someone, who said he was a computer programmer, which language he used.

    He said: English

  • pseudonymus coward (unregistered)

    I'm not so much shocked that a person who can't program got a CS degree, but that a total idiot got a CS degree.

  • JamesGecko (unregistered)

    Actually... I honestly never had to write a factorial function in any of my CS classes. Not to say we never covered recursion.

    I note that none of the example functions here cover what to do with negative numbers. Is there a proper way to handle them? I'm pretty sure my way isn't exactly the preferred method...

    #include <stdio.h>

    int main() { printf("%d\n", factorial(0)); return 0; }

    int factorial(int n) { if(n < 0) printf("Undefined for "); return n; if(n = 0) return 1; while(n > 1) return n * factorial(n - 1); return n; }

  • Shinobu (unregistered) in reply to Anon

    Where I'm from those are considered simple terms... if where you're living this is not so, then perhaps your nation needs collective evening classes.

  • Dave (unregistered) in reply to Cyrus

    Teamwork is for losers.

    ;)

  • ChrisB (unregistered) in reply to bstorer
    bstorer:
    Joseph:
    I just find it amazing that people who code like that can actually graduate!
    Don't be. In my senior level software engineering class, we worked on a program that had been developed by, I believe, the two previous semesters. I rewrote so much of the code it was mind-boggling. There were 3 separate functions to convert a MFC CString into a char*: one worked properly, but was still slower than the built-in methods, one had an off-by-one error, and one didn't always allocate enough space, so you could do buffer overruns with it. I was blown away at the time, because these people had all presumably graduated and found jobs. This site will never run out of content.

    I still remember sitting in the labs during my compsci undergraduate course, and I had people asking me how to do things in MS Word! If these people couldn't even use Word, I dread to think what their code was like.

  • Dust (unregistered)
    Kardi:
    No way is this even possible; but then again I guess anything is possible at WTF University.

    I just can't fathom how someone can't know the terminoligy; if you don't have the skills ... make sure you can BS with the best of them. Oh, what as that 'n' doing??

    http://www.FireJayPa.com

    I sure know what recursive and iterative is but I actually had to look up what factorial is since i a) Do not have english as my primary language b) Did not remember the term from my math courses either

  • LostBoy (unregistered) in reply to Noamsml

    I'm not a programmer, I can't code, I wrote simple shell scripts a decade ago and I know what recusion is.

  • Pooma (unregistered) in reply to gsmalleus
    gsmalleus:
    Noamsml:
    KattMan:
    pitchingchris:
    Doesn't use the input parameter and doesn't reuse the variable a, except to hold the number. Course, we all were dumb at one point, but at least we know what recursion was when we graduated.

    I never regurgitated from college, hell I never went, and even I know what recursion is.

    Same here. I'm a f'ing high school student and even I know what recursion is.

    Oh, and by the way:

    
    int factorial(int n)
    {
    if (n=0) return 1;
    else return n * factorial n;
    
    //if the universe has gone insane, return 42 (cannot be a factorial)
    return 42;
    }
    
    

    But evidently you haven't gotten to the part about infinite loops yet.

    else return n * factorial n-1;

    Won't even be an infinite loop. In Java it won't compile, in C it'll drive you nuts working out why n=0 (O.P meant n==0) is breaking your behaviour.

  • Pooma (unregistered) in reply to Aaron
    Aaron:
    Actually it will always return 1 because if (n=0) always returns true (successful assignment)

    Erm, nope. n=0 returns the value assigned, which is 0, and therefore is logically false.

  • (cs) in reply to Justin
    Justin:
    No No, it's not twelve. 'i' gets modified in the loop. So, we have a function that returns the answer to life, the universe, and everything.

    I thought you were speaking figuratively. Then I went through it in my head and...

    wow...

    Also:

    int fac_recursive(int n)
    {
      return (n>1)?n*fac_recursive(n-1):1;
    }
    
    int fac_iterative(int n)
    {
      int fac=1;
      for (int i=2;i<=n;i++) fac*=i;
      return fac;
    } 
    

    Although when in a job interview, I would probably avoid going for minimum number of lines in favor of readability. After all, these people want to use your code, not enjoy your artwork.

  • (cs) in reply to JamesGecko
    JamesGecko:
    I note that none of the example functions here cover what to do with negative numbers. Is there a proper way to handle them?
    Yes there is: you avoid the whole problem. Like Drahflow already pointed out, and like I used in my iterative solution earlier, you can define the function factorial for unsigned integers only. That way you can't even pass a negative number to the function at all, so no error checking is needed in the factorial function. Like DrahFlow I too have trouble understanding why almost all solutions posted here are defined for signed integers.

    I've seen it a lot in production code too: rather than choosing the types to match the domains of the functions or the problems, people use some generic type and fill the code with asserts or exceptions. Someone please explain to me what the advantage of that is?

    One bit of range checking I have not yet seen is a platform-independent way to calculate (preferably at compile-time) the largest value for n for which n! will not overflow the unsigned integer type, so we can test n against it and throw an exception. Now that would be an interesting interview question ;)

  • Cale (unregistered) in reply to bstorer

    Well, I can compute an approximation. What you really want is Gamma(z+1) = 12, since it's Gamma(n+1) = n! when n is a natural number.

    Here's the first few digits:

    z = 3.522397909560105235767834115692276
          219439097895455036921925398541282
          553985235645311467070583696745434
          740872224171322753839387281398028
          581374223939906311336693171103164
          216574797785658475428257574942725
    

    It's fairly close to 10*(3/10)^(13/15), the difference being about 4.9*10^(-8).

  • (cs)

    #!/bin/sh

    lynx -dump "http://www.google.co.uk/search?q=${1}!" | egrep "!)? ="

  • (cs) in reply to Ryan
    Ryan:
    I really wish people would stop teaching recursion using factorial as an example.

    Factorial is the WORST possible example of recursion there is. It's slower and less efficient to do it recursively than iteratively.

    Why don't they use actual recursive things for teaching recursion - like trees or something.

    I learned recursion in school, and thankfully I was smart enough to realize when to use it and when not to. I've seen recursion used so many times in inapropriate places that it sickens me.

    For a great discussion of it, try picking up a copy of "Code Complete"

    Isn't recursion always going to be less efficient than the equivalent iterative function? Even navigating trees can be done iteratively, and you don't have to worry about that stack blowing up while it is running. Students should be taught it as a neat trick than can do (so if they do ever do it, they don't do it wrong), and then promptly taught not to do it.

    There is one good thing about recursion. When (in Java) it throws a StackOverflowError, you get a really neat looking stacktrace back!

  • Lemb (unregistered) in reply to ChrisB
    ChrisB:
    I still remember sitting in the labs during my compsci undergraduate course, and I had people asking me how to do things in MS Word! If these people couldn't even use Word, I dread to think what their code was like.

    I understand what you mean, but remember that being a good programmer is not the same as knowing how to use 'office' programs.

    An example: I met a guy who was expert in big systems, but knew only the basics about windows and such. He was always annoyed when friends asked him questions about windows/word/whatever: they did not understand that working in computers/programming does not make you expert in windows problem solving.

    Another example: my binome at university. She was really quite clueless about computers -PCs- in general, because she did not have much interest in them as such. However, she was quite a good programmer and worked on difficult financial project in C++ after we graduated.

    In summary: ignorance of Word is not enough to say that someone is a bad programmer. Still, in the environment you describe, it is certainly a bad omen...

  • Lemb (unregistered) in reply to not a programer...
    How did this get so many hits?? Do you programers find this funny/tragic?

    As a programmer, I'd say I find it pathetic.

    And, from my experience, it is unfortunately quite common to meet such ignorance. At least, I met a lot of so-called programmers who were not much better than that.

    The most surprising case was the programmer (studied programming, worked as a programmer) who did not WANT to program! Why did he choose this kind of job then? (In the end he switched to QA were he is quite good I've been told)

  • Raedwald (unregistered) in reply to Joseph

    Have you considered that he lied that he graduated?

    A Test Manager friend of mine complains about exagerations on CVs (resumes) that border on outright lies. She asks anyone who claims the ability to program in C to write a "hello, world" program. And anyone who claims SQL knowledge to write a query that requires a two-table join.

    About 40% fail.

  • F.M. (unregistered)

    That f'd code is the result of not knowing the difference between a Math/CS degree and a CSEE degree. Sure they are both a CS degree, and both of them will teach you how to put code into a computer, but that's where it ends.

    The code looks like a CSEE wrote it (thinking, uhh, you want some kind of math thinggy, ok, But I hate math, don't you have a driver I can code up for you)

  • bill (unregistered) in reply to American Programmer
    American Programmer:
    bill:
    KattMan:
    An abstract class is one that adheres to a defined interface but does not provide functionality. Used as a base class it lets derived classes know they have to implement certain method and provide the functionality for those methods.

    Do I win a cookie?

    Not quite, an abstract class can provide functionality (an interface does not provide functionality).

    I would say this is a good definition: An abstract class is a class which can not be directly instantiated.

    This is more information than I asked for, but I would still accept it: An abstract class is a class which can not be directly instantiated. In order to instantiate an abstract class one must create a class which inherits from the abstract class and implements the abstract methods (aka pure virtual methods/functions depending on the language background of the interviewee). After that a person can instantiate a variable of the abstract type by calling the constructor of the derived type.

    Kattman would be given additional prompting for more details.
    bill gets part one right - but skips part two. "Why would I want one?"

    What is the key advantage in having an abstract base class? When would you create one? Answering this correctly implies you know more than just how to ape the forms and parrot the propaganda and platitudes and demonstrates that you have some idea of why you're doing what you're doing. Also, believe it or not, the motivations for doing this are somewhat language dependent. An awareness of that is a bonus.

    I should have qualified my answer: When interviewing someone I always ask that as 2 separate questions. This has me avoid getting a totally off the wall answer. One person I asked told me that an abstract class is a class with the name "Abstract". I had to ask him to show me on a whiteboard and he gave this (C#):

    public class Abstract {
    }
    

    So I asked why abstract was capitalized (this person lowercased class names in previous questions). He stated that it didn't compile if it was all lowercase. At this point I just had to ask why an abstract class was useful. He said (and I quote) "I suppose you could put stuff there that you were not sure about or not finished or that could be used in a bunch of places." Needless to say, he didn't get hired. Since then, I don't bother asking why until after the person has given a decent answer as to what something is.

    For all: As to why an abstract class is useful, an abstract class allows you to provide implementations to some methods so you wouldn't have to duplicate them in derived classes. This makes it attractive for a non-leaf classes in a planned inheritance model.

  • waffles (unregistered) in reply to nwbrown
    nwbrown:
    Isn't recursion always going to be less efficient than the equivalent iterative function? Even navigating trees can be done iteratively, and you don't have to worry about that stack blowing up while it is running. Students should be taught it as a neat trick than can do (so if they do ever do it, they don't do it wrong), and then promptly taught not to do it.

    There is one good thing about recursion. When (in Java) it throws a StackOverflowError, you get a really neat looking stacktrace back!

    With a language that supports tail recursion, the performance of the recursive and iterative solutions will be the same. In some cases, the recursive solution will actually be significantly faster, as it's easier to memoize a recursive function than an iterative function. The problems with recursion are problems with the languages most people use, not with the concept.

  • Leahn Novash (unregistered) in reply to Anonymous
    Anonymous:
    The specification calls for a function that will find the factorial of ANY given number. A 4-byte signed integer can't hold anything larger than 12 factorial. Captcha: Case statement, anybody?

    What about using a long? KISS, guy, KISS. But if you REALLY want to make a function that would work for ANY integer, then I am afraid you'd have to use bignum tricks for it. It can still be recursive, mind you. Just way harder and trickier to do. Anyone wants a go on it?

    By the way, the CAPTCHA Test today is RIAA. Any thoughts?

  • (cs) in reply to gwenhwyfaer
    gwenhwyfaer:
    ashton:
    The complexity of the naïve recursive definition of fib is far worse than n^2 -- it is exponential, but it drops to linear with a simple memoization scheme.
    Ouch - yes, you're right... which kind of reinforces what I was saying, that fibonacci is way worse than factorial for illustrating recursion!
    No, it's better for illustrating recursion because it's more complex and makes a better example. It's worse in the real world (unless your language has "a simple memoization scheme" built-in), but th at has nothing to do with its usefulness as a teaching example.
  • (cs) in reply to rjnewton
    The assertion that the factorial of 0 is 1 is both meaningless in terms of the generation of factorials, and pointless, since you still have to limit the domain of the function to non-negative integers. What's the point in defining a factorial of 0?

    Because Γ(1) is 1 and x! == Γ(x+1)? And Γ(x) where x is a negative integer is infinite/indeterminate?

  • (cs) in reply to Beowulff

    Why not just throw the exception when it overflows?

    <pseudocode type="text/c-src;with-exceptions"> unsigned factorial(unsigned x) throws ERANGE { unsigned y = factorial(x-1); unsigned r = y*x; if(r/y < x) throw ERANGE; return r; } </pseudocode>

    To answer your other concern - not all languages have an "unsigned integer" type.

  • YourMoFoFriend (unregistered) in reply to Rugged individualist
    Rugged individualist:
    So-called "teamwork" is the use of group dynamics to minimize the influence of any single individual and to reduce the number of management layers. Based on the communist belief system. In the gulags, where they thought they came up with it, it was called a "work brigade", and allowed large numbers of prisoners to work outside the fence with relatively few guards. Nothing to do with working together co-operatively, although management certainly wants the employees to play nice.
    <sarcasm ON>I totally agree because working in a labor camp is so-o-o very much like working in a development team<sarcasm OFF>
  • PellePlutt (unregistered) in reply to Random832

    Isn't the n-choose-k dependant on 0!=1??

    nchoosek(2,2)=n!/(k!*(n-k)!)=2!/(2!*0!)=2/2=1 QED.

    Just a thought...

  • (cs) in reply to Anon

    Let's suppose you need a factory class that automatically selects a class to instantiate based on some opqaue conditions bound to the parameters passed to the factory.

    All classes instantiated have to respect a certain interface therefore you can either:

    1. create each and every class separately to follow the interface they implement

    2. create one class first with all the needed helper methods then subclass it for others (again adding needed helper methods)

    3. create a base abstract class containing all the shared logic, then subclass it for each and every class needed adding only the part that differs in implementation and only the needed helper methods

    I think I don't have to explain why option 1 is bad. If you think option 2 is acceptable, think about feeding your code to a Doxygen-like (or pydoc-like) parser and think of the results.

  • (cs) in reply to greg
    greg:
    Obligatory Whitespace solution:

    // :D

    You've got an error in line 3. It should be

    instead.

  • (cs) in reply to Random832
    Random832:
    No, it's better for illustrating recursion because it's more complex and makes a better example. It's worse in the real world (unless your language has "a simple memoization scheme" built-in), but th at has nothing to do with its usefulness as a teaching example.
    I'd dispute your apparent notion that teaching examples should ignore real-world context. If you're going to use fibonacci to teach recursion, students deserve to know why it's really not a good idea to do it that way in the real world, and how to make it acceptably fast (the "simple memoisation scheme", laziness, converting to iteration, whatever) - in fact, it might well serve as an excellent introduction to the whole topic of "what happens when your recursive solution performs abysmally", or "why recursive definitions aren't necessarily good definitions".

    But for teaching recursion per se, I'd suggest mergesort or binary search are much better starting points. The algorithms are dead simple, do useful things in the real world, and show up the real strengths of recursion. In the purely numerical domain, the Ackermann function (and yes, the humble factorial) might be another good example; A(m,n) could even be used to illustrate the point that divide-and-conquer type algorithms tend to be naturally recursive.

    Good and bad practices should be taught from the simplest examples up; they're too hard to shift once they're ingrained.


    (And to head off all the anal types out there - yes, I'm sure there are naturally iterative D&Cs; yes, I appreciate how extremely clever you must be to know about them; no, I don't really give a flying fuck what they are.)

  • Someone (unregistered) in reply to Noamsml
    Noamsml:

    Same here. I'm a f'ing high school student and even I know what recursion is.

    Oh, and by the way:

    
    int factorial(int n)
    {
    if (n=0) return 1;
    else return n * factorial n;
    
    //if the universe has gone insane, return 42 (cannot be a factorial)
    return 42;
    }
    
    

    Shouldn't that be

    unsigned very very long long operator!(unsigned int n)
    {
        return n ? n*!(n-1) : 1;
    }
    

    ! is not written 'factorial', so define it that way. You should also leave room for large results. This code requires the C++ beyond the one with whitespace overloading, but hey, who cares. (o, and you are missing a '-1' in your recursion call)

  • (cs) in reply to Random832
    Random832:
    Why not just throw the exception when it overflows?
    You can indeed, but it introduces an extra arithmetic operation into every level of recursion or iteration, doubling the run time of the algorithm. A simple comparison with a constant is much more preferred.
    Random832:
    To answer your other concern - not all languages have an "unsigned integer" type.
    No, but most solutions so far seem to be C, C++ or Java and those languages all have unsigned types - why not use them? I'd even go so far as call it a design error if you didn't.
  • (cs)

    Just for fun, Ruby:

    def fact(i) i<2 ? 1 : i * fact(i-1) end

    or, iteratively (perhaps) behind the scenes:

    def fact(i) (1..i).inject(1) {|m, n| m*n} end

    and don't worry too much about overflow:

    fact(42) => 1405006117752879898543142606244511569936384000000000

    fact(300) => 306057512216440636035370461297268629388588804173576999416776741259476533176716867465515291422477573349939147888701726368864263907759003154226842927906974559841225476930271954604008012215776252176854255965356903506788725264321896264299365204576448830388909753943489625436053225980776521270822437639449120128678675368305712293681943649956460498166450227716500185176546469340112226034729724066333258583506870150169794168850353752137554910289126407157154830282284937952636580145235233156936482233436799254594095276820608062232812387383880817049600000000000000000000000000000000000000000000000000000000000000000000000000

  • stiggy (unregistered)

    Public Function Paula() As String Paula = Really("Brillant") End Function

    Private Function Really(strAppend As String) As String Really = "Really " & Really(strAppend) End Function

    Stack overflows are fun ;-)

  • stiggy (unregistered)

    D'Oh! A flawed post to a WTF about recursion. I must have been aiming for irony, or something. Using VB, too....

    Oh, well; second iteration:

    Public Function Paula() As String Paula = Really("Brillant") End Function

    Private Function Really(strAppend As String) As String Really = Really("Really " & strAppend) End Function

Leave a comment on “F'd Factorial”

Log In or post as a guest

Replying to comment #:

« Return to Article