• Aaron (unregistered) in reply to tlf

    Actually it will always return 1 because if (n=0) always returns true (successful assignment)

  • (cs) in reply to Random832

    You know, some people might regard replying to a post that says

    (Of course, the O()s quoted assume that addition and multiplication are always O(1), but hey...)
    with
    Are you selling this computer which can calculate basic math functions in O(1) time for arbitrarily large/precise arguments? Because I would very much like to buy one.
    - especially when they would have had to explicitly delete the aforementioned snippet - as callow and intellectually dishonest...
  • Alan (unregistered)

    Just yesterday I had someone in for a c# developer position. I gave them a 9 question aptitude test. Question 9 was:

    Write a c# function that returns true if the input is zero or greater than 5.

    They answered:

    int a; if(a=0 or >5) { return(true); } else { return(false); }
  • digislave (unregistered) in reply to Will
    Will:
    Not a computer science graduate:
    Written in a minute or two by myself, with no reference to anything:
    function factorial( $a )
    {
    	if ( $a <= 1 )
    		return( $a );
    		
    	return ( $a * factorial( $a - 1 ) );
    }

    Recursion! Factorials! Rubbish, but actually works! Doesn't return twelve!

    Unfortunately, I didn't study computer science at university - in fact, I have no computing qualifications whatsoever. Sorry.

    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

  • digislave (unregistered) in reply to Noamsml
    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;
    }
    
    

    Nice infinite loop.

    Should be: else return n * factorial(n-1)

  • none (unregistered) in reply to bstorer

    It is about -1.081230492.

  • American Programmer (unregistered)

    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.

  • Lee (unregistered) in reply to Random832
    Random832:
    Sam:
    Guru Buckaroo:
    DZ-Jay:
    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;

    }

    Dont you mean it will return 1 every time? The if statement will always be true..

    Actually, the if statement will always be false. therefore, it will recurse infinitely.

    The statment "n=0" is just like any other assignment statement, and evaluates to true. (assuming this IS c++)

    It will never get to the else, or the part about the universe having lost all sanity.

    CAPTCHA: kungfu!!

  • none (unregistered) in reply to bstorer
    bstorer:
    sxeraverx:
    Sorry about that, gamma(4.5224) = 12, so:

    3.5224! = 12

    My bad.

    My hero!

    This is a poor solution that falls under a local minimum, -1.081230492 corresponds to the global minimum.

  • root (unregistered)

    h=0 returns false.

    int factorial(unsigned int n) { if (n<2) return 1;

    return (n *factorial(n-1)); } //took me less than 20 seconds to write. craaazy

  • wkempf (unregistered) in reply to Lee

    Wow! Just, oh wow! Why do people post condescending remarks, when they themselves don't have a clue? Assignments in C and C++ return the result of the assignment, not true. Try it and blush:

    int main(int argc, char* argv[]) { int n; if (n = 0) printf("n=0\n"); if (n = 1) printf("n=1\n"); return 0; }

  • ripsaint (unregistered)

    When I read this I laughed. We must be interviewing the same people. My most recent favorite interview of a "Senior Java Programmer" went like this:

    Me: What is the base class of all other classes in java? Interviewee: I don't know. Me: It's called "Object" Interviewee: Oh, I've never seen that.

    The rest of the interview wasn't much better.

  • (cs) in reply to ripsaint
    ripsaint:
    When I read this I laughed. We must be interviewing the same people. My most recent favorite interview of a "Senior Java Programmer" went like this:

    Me: What is the base class of all other classes in java? Interviewee: I don't know. Me: It's called "Object" Interviewee: Oh, I've never seen that.

    The rest of the interview wasn't much better.

    Let me guess, you decided not to hire him as a senior programmer, but two weeks later he was introduced to you as the new Director of IT.

  • (cs)

    in scheme r5rs

    (define (! n)
      (cond ((> n 0) (* n (! (- n 1))))
            ((<= n 0) 1)))
  • Andrew (unregistered) in reply to Lee
    Lee:
    The statment "n=0" is just like any other assignment statement, and evaluates to true. (assuming this IS c++)

    It will never get to the else, or the part about the universe having lost all sanity.

    CAPTCHA: kungfu!!

    Don't know what C++ you're using, but in my compiler assigment evaluates to the value of the thing being assigned. This is frequently abused as such:

    int a, b, c; a = b = c = 42;

  • Leahn Novash (unregistered) in reply to Sam
    Sam:
    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;

    }

    Dont you mean it will return 1 every time? The if statement will always be true..

    No, it won't. The program will use the value of n as input for the if, and it happens to be 0, and will evaluate to false.

  • Darien H (unregistered) in reply to Anon
    Anon:
    I found asking people to explain what object orientated programing is was a good way to filter. It's amazing that some people can attempt to answer that question without using the word "object". I do that one in the phone interview.

    Well, if they replaced "object" with "thingy", they might be dev material, but with communication skill issues. If they replaced "object" with "instance", that's a little better.

  • A programmer (unregistered) in reply to tlf

    Actually, that code was totally wrong. This function actually works...

    int factorial(int n) { if(n == 0) { return 1; } return n * factorial(n-1) }

  • waffles (unregistered) in reply to Yariv
    Yariv:
    A. Church:
    Yariv:
    Recursion is always slower than iteration, it is obvious.

    Another mind destroyed by languages without proper support for tail-recursion...

    The fact the the compiler can change your algorithm, replacing the recursion you wrote with a loop is irrelevant. If you run a recursion, it is slower than iteration. Simple. Leave optimization issues aside, even if you write your code so it will be optimized.
    Tail recursion in a language designed to support it is not done by the compiler turning the recursion into a loop. It's not an "optimization" any more than more than a compiler deciding not to insert a bunch of sleep statements in your code is. I certainly don't see any code that says "allocate a bunch of new memory over and over" in the following code, because it isn't there:

    (define (! n)
      (cond ((> n 0) (* n (! (- n 1))))
            ((<= n 0) 1)))
  • Jason (unregistered) in reply to ahgan

    Unfortunately for n = 0, while(--n) will result in an infinite loop.

  • Longtime C guy (unregistered)

    The python version:

    def factorial(n) : return (1 if n <= 1 else reduce (lambda x, y : x * y, range(1, n + 1)))

  • ahgan (unregistered) in reply to 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;
    }
    
    

    Will always return 0. The 'if' sets n to 0 and the compiler can then optimize the code and remove the recursive call completely and just return 0.

    CAPTCHA: sanitarium <-- perfect

  • Todd (unregistered) in reply to Kardi

    My operating systems course started with 60 people. Like 20 made it to the end of the year and 12 actually passed. All to learn a bunch of IBM370 we'll never used again.

    Pretty much every CS course starts with twice as many people than it ended with.

  • (cs) in reply to Leahn Novash
    Leahn Novash:
    Sam:
    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;

    }

    Dont you mean it will return 1 every time? The if statement will always be true..

    No, it won't. The program will use the value of n as input for the if, and it happens to be 0, and will evaluate to false.

    le sigh

    It matters not what the value of n was when it was passed in, it is assigned the value of 0.

    In C... x = y = 6; What is the value of x? It is 6 as they are all assignments and the assignment returns the value assigned rather then a flag indicating success.

    In VB x = y = 6 Only the first = is an assignment the second is a equality operation. So if y was 6 it returns true, otherwise false.

    Following this: if (n=0) return 1; N is assigned 0 and returns the results of that assignment which is 0. 0 is false so it hits the else and recurses forever.

  • Bill (unregistered) in reply to Noamsml
    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;
    }
    

    .

    I love it when a high school student blows the stack. WTF

  • (cs) in reply to Todd
    Todd:
    My operating systems course started with 60 people. Like 20 made it to the end of the year and 12 actually passed. All to learn a bunch of IBM370 we'll never used again.

    Pretty much every CS course starts with twice as many people than it ended with.

    The education I did receive (only stayed a year for a diploma, no degree) we started with 35-40 students, only 7 graduated. So that is 20% or less that actually finished. Most of the drop outs were withing the first three courses.

  • (cs) in reply to Bill
    Bill:
    I love it when a high school student blows the stack. WTF

    Usually happens right after stacking the blow. Man I hate it when that happens.

  • Buttons (unregistered)

    should it be:

    public int factorial(int n) { int a = 1;

     for (int i = 1; i < n; i++)
     {
          a *= i;
     }
    
     return a;
    

    }

    or maybe

    public int factorial(int n) { if(n>1) return n * factorial(n-1); }

    In guess the graduate student wasn't THAT far off... i mean, he had the function name, variable AND a for loop :P

  • PseudoNoise (unregistered) in reply to Aaron

    That's only in C. In C++, there's no need to test for assignment because it will throw an exception if it fails.

    (snicker)

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

    That's only in C -- C++ will throw an exception if assignment fails.

    (drat, that would have been a whole lot funnier if I'd hit quote instead of reply)

  • Jason (unregistered) in reply to Welbog

    C++

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

  • A. Church (unregistered) in reply to Jason
    Jason:
    C++

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

    I hate code like this much more than the readable-but-wrong kind...

  • PseudoNoise (unregistered) in reply to Jason
    Jason:
    C++

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

    pfff, that's not C++. THIS is C++:

    template <int N>
    struct Factorial 
    {
        enum { value = N * Factorial<N - 1>::value };
    };
    
    template <>
    struct Factorial<0> 
    {
        enum { value = 1 };
    };
    
    // Factorial<4>::value == 24
    // Factorial<0>::value == 1
    void foo()
    {
        int x = Factorial<4>::value; // == 24
        int y = Factorial<0>::value; // == 1
    }
    
  • Harrow (unregistered) in reply to Anon
    Anon:
    gwenhwyfaer:
    Anon:
    I found asking people to explain what object orientated programing is was a good way to filter. It's amazing that some people can attempt to answer that question without using the word "object". I do that one in the phone interview.
    Oh, come now:

    "A style of programming in which each entity comprises both information and the operations that manipulate that information; all entities are regarded as self-contained and autonomous, communicating only by invoking each other's operations."

    Well done. And you're not hired because of your lack of ability to explain a concept in SIMPLE TERMS. That's why I like the question, it weeds out both people who don't actually know the concept and those who know the concept but can't communicate for shit.

    I would also like to use this question to weed out people who can't communicate well, but I will need help evaluating their answers. Could you please give an example of an explanation of this concept in simpler terms.

    Thx in adv.

    -Harrow.

  • (cs) in reply to A. Church
    A. Church:
    Jason:
    C++

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

    I hate code like this much more than the readable-but-wrong kind...
    Why? Nothing wrong with that other than that it handles negatives incorrectly. One of the best snippets so far.

  • Jason (unregistered) in reply to PseudoNoise
    PseudoNoise:
    Jason:
    C++

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

    pfff, that's not C++. THIS is C++:

    Templates gah! My mind esplode!

    Crap, I misplaced my semicolon. Oh well. Thank God I already have a job.

  • abitslow (unregistered)

    I guess to me this goes to prove how easy it is to screw up, if you dont test your own code.

    oh buttons, I susspect you meant i<=n

  • Jason (unregistered) in reply to Welbog
    Welbog:
    A. Church:
    Jason:
    C++

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

    I hate code like this much more than the readable-but-wrong kind...
    Why? Nothing wrong with that other than that it handles negatives incorrectly. One of the best snippets so far.

    Sonofa...!

    Let me try again: int factorial(int n){n=abs(n);(n==0?return 1:return n*factorial(n-1));}

    Not sure how to handle negatives.

  • (cs) in reply to Harrow
    Anon:
    gwenhwyfaer:
    Anon:
    I found asking people to explain what object orientated programing is was a good way to filter. It's amazing that some people can attempt to answer that question without using the word "object". I do that one in the phone interview.
    Oh, come now:

    "A style of programming in which each entity comprises both information and the operations that manipulate that information; all entities are regarded as self-contained and autonomous, communicating only by invoking each other's operations."

    Well done. And you're not hired because of your lack of ability to explain a concept in SIMPLE TERMS. That's why I like the question, it weeds out both people who don't actually know the concept and those who know the concept but can't communicate for shit.

    But he did communicate simply within the context of the participants. If you can't understand a tech explaining this to a tech, why are you running interviews? If you want him to explain it in "simple terms" ask him how he would explain it to his mother.

    Trying to evaluate to many factors in one question is a failure of the interviewer, not the interviewee.

  • Jason (unregistered) in reply to A. Church
    A. Church:
    Jason:
    C++

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

    I hate code like this much more than the readable-but-wrong kind...

    Yeah me too, but its fun to write it.

  • (cs) in reply to Jason
    Jason:
    A. Church:
    Jason:
    C++

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

    I hate code like this much more than the readable-but-wrong kind...

    Yeah me too, but its fun to write it.

    heh, geek.

  • AM (unregistered) in reply to Noamsml

    Umm... I think that ought to be a else return n * factorial n-1

    AM

  • (cs) in reply to Jason
    Jason:
    Let me try again: int factorial(int n){n=abs(n);(n==0?return 1:return n*factorial(n-1));}

    Not sure how to handle negatives.

    Strictly speaking n! is only defined for n >= 0, so it should return NaN or throw an exception if n < 0. (Bonus points if you throw NaN, though.)

  • A programmer (unregistered) in reply to tlf

    Actually, that code was totally wrong. This function actually works...

    int factorial(int n) { if(n == 0) { return 1; } return n * factorial(n-1) }

  • wkempf (unregistered) in reply to Jason
    Jason:
    A. Church:
    Jason:
    C++

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

    I hate code like this much more than the readable-but-wrong kind...

    Yeah me too, but its fun to write it.

    Try again. That won't compile.

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

    Ignoring negative input issues.

  • Brian Boyko (unregistered)

    Oh god. I'm not even a programmer and that's horrible!

  • (cs) in reply to Jason
    Jason:
    Unfortunately for n = 0, while(--n) will result in an infinite loop.
    No, it won't.

    There are not an infinite number of negative integers, therefore n will eventually wrap around and become positive, which will eventually count down to 0.

  • (cs)

    I can't believe none of you can do factorial in O(1). Before you argue pedantry, none of the other implementations in C/C++ could exceed the values of their defined return types, either.

    static const unsigned long long factorial_lookup[] = { 1LL, /* 0 */ 1LL, /* 1 */ 2LL, /* 2 */ 6LL, /* 3 */ 24LL, /* 4 */ 120LL, /* 5 */ 720LL, /* 6 */ 5040LL, /* 7 */ 40320LL, /* 8 */ 362880LL, /* 9 */ 3628800LL, /* 10 */ 39916800LL, /* 11 */ 479001600LL, /* 12 */ 6227020800LL, /* 13 */ 87178291200LL, /* 14 */ 1307674368000LL, /* 15 */ 20922789888000LL, /* 16 */ 355687428096000LL, /* 17 */ 6402373705728000LL, /* 18 */ 121645100408832000LL, /* 19 */ 2432902008176640000LL /* 20 */ /* 51090942171709440000L exceeds 64-bit value */ };

    unsigned long long fast_fac(unsigned int n) { if(n > 20) return 0; return factorial_lookup[n]; }

    /* here's my original, for your viewing pleasure */ unsigned long long fac(unsigned int n) { unsigned long long p = 1;

    for( ; n > 1; n--) p *= n; return p; }

  • Feynman (unregistered) in reply to Anon
    Anon:
    gwenhwyfaer:
    Anon:
    I found asking people to explain what object orientated programing is was a good way to filter. It's amazing that some people can attempt to answer that question without using the word "object". I do that one in the phone interview.
    Oh, come now:

    "A style of programming in which each entity comprises both information and the operations that manipulate that information; all entities are regarded as self-contained and autonomous, communicating only by invoking each other's operations."

    Well done. And you're not hired because of your lack of ability to explain a concept in SIMPLE TERMS. That's why I like the question, it weeds out both people who don't actually know the concept and those who know the concept but can't communicate for shit.

    I cannot explain it in terms you understand, because no one understands it in terms you understand.

  • (cs)

    Any employer who asks me this would regret it:

    //Initialize the variable out to 1 before calling this
    void factorial(int in, int *out) {
            *(&in-1)-=5-5*(1/in);
            *out*=in--;
    }

Leave a comment on “F'd Factorial”

Log In or post as a guest

Replying to comment #:

« Return to Article