• iMalc (unregistered)

    Hmm, I would have asked whether he wanted the recursive, iterative, lookup table, or compile-time template meta-programing version.

  • Daniel (unregistered) in reply to KevB

    I so would've used n.

  • Antony Curtis (unregistered)

    int factorial(int i, int a=1) { if (i <= 1) return a; return factorial(i - 1, a * i); }

    This one allows the compiler to do some optimization and can be as efficient as a loop.

  • (cs)

    I'm amazed at the amount of ways in which you guys have managed to break or mangle the factorial function.

    Having said that, I guess I have to prove I'm not one of you:

    int factorial(int n)
    {
    	assert(n >= 0);
    	if (n > 1)
    	    return n * factorial(n - 1);
    	else
    	    return 1;
    }
    But since this isn't Python, you could could just as well do it in O(1):
    // Assuming 32-bit integers
    const int fact_lookup[13] = { 1, 1, 2, 6, 24, 120, 720, 5040,
    	40320, 362880, 3628800, 39916800, 479001600 };
    int factorial(int n)
    {
    	assert(n >= 0 && n <= 12);
    	return fact_lookup[n];
    }
  • Lee (unregistered) in reply to Andrew
    Andrew:
    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;

    OH GOD NO i hate being wrong... but yeah i feel kinda stupid now... haven't done c++ in years and apparently took a real shortcut in remembering that :(

    In other news, where I work now they expect no prior language knowledge, so the entrance test was a language-irrelevant logic test called the WCOAT test. Based on the highly-confidential scores of myself and my coworkers, it is pretty accurate. (and felt very appropriate as i was taking it)

    /brb killing self

  • (cs) in reply to gwenhwyfaer
    gwenhwyfaer:
    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...

    When I respond to just one statement, I don't always copy the whole thing, and I don't always read the parts i'm not copying. Not everyone hits "quote" all the time - TRWTF is having a "reply without quoting" option in the first place.

    Some people might regard making an accusation in the format "Some people might regard..." instead of having the balls to stand by your own words as a form of cowardice.

  • (cs) in reply to Lee
    The statment "n=0" is just like any other assignment statement,
    True.
    and evaluates to true.
    False.

    It evaluates to the value that was assigned. Which is 0. Which is false.

  • Another American Programmer (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.

    "Certain ethnic backgrounds"? Nice code words, there. And I'm sure no one from other countries will read your rant and think about how arrogant, etc Americans are.

    I've taught CS and engineering at a state university also, and if you think that assignment collaboration and teamwork are restricted to "certain ethnic backgrounds", you're fooling yourself.

    I'm against expanding H1-B visa limits, but your non sequitur rant makes me embarrassed to be on the same side.

  • (cs) in reply to Another American Programmer
    Another 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.

    "Certain ethnic backgrounds"? Nice code words, there. And I'm sure no one from other countries will read your rant and think about how arrogant, etc Americans are.

    I've taught CS and engineering at a state university also, and if you think that assignment collaboration and teamwork are restricted to "certain ethnic backgrounds", you're fooling yourself.

    I'm against expanding H1-B visa limits, but your non sequitur rant makes me embarrassed to be on the same side.

    I agree. I am sure there are just a many stupid Americans as there are stupid (insert favorite ethnicity here). The real problem is we Americans are supposed to be leaders in the free world. Nice example we are setting here isn't it?

  • ashton (unregistered) in reply to gwenhwyfaer

    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.

  • Anon (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.

    That's actually an excellent way to describe OO programming... Probably quoted from a book, but very easy to understand.. And we're glad we don't get the job. We don't want to work for anyone (i.e. you) who's too stupid to understand three-syllable words..

  • Michael (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.

    I hope I am not alone in wishing you would keep your political opinions to yourself (or at least air them on a suitable political site.)

    As regards working as a team, teamwork is one of the most sought after properties of programmers in the business world. There are few places these days where you can sit on your own and code your own stuff - most programmers have to work together with customers/users, DBAs, server techs, testers, project managers, external service providers, not to mention other coders.

    On some projects, my responsibilities have been less than 25% actual coding, and the rest of the time I have to make sure other people do their stuff. That's how you get things done.

  • (cs) in reply to bstorer
    bstorer:
    On a related note, does anyone want to solve for z in G(z) = 12 where G is the Gamma function? Because that's like a factorial.

    There's no easy solution other than Newton's method using series approximations for gamma and digamma. Nor is there a most-complex-domain-converging series-like expression that I can find, like there is for the gamma function itself.

    Like, you can solve for the limit of the upper and/or lower incomplete gammas through the inverse of regularized gamma. (Regularized gamma is G(a,z)/G(a) with parameters a and z) But it only solves for the 'z' parameter in G(a,z)/G(a), not the 'a' parameter. But in general you can't solve for 'a' in G(a) (imagine 'G' is the greek gamma symbol).

  • American Programmer (unregistered) in reply to KattMan
    "Certain ethnic backgrounds"? Nice code words, there. And I'm sure no one from other countries will read your rant and think about how arrogant, etc Americans are.

    I've taught CS and engineering at a state university also, and if you think that assignment collaboration and teamwork are restricted to "certain ethnic backgrounds", you're fooling yourself.

    You do understand the difference between a heuristic and an algorithm, right? That is a heuristic and the underlying basis is a function of culture. I make no value judgements apart from every semester I have to bust up one or more of these little work groups and fail its members for the course because they all turn in the identical code, often cribbed from some book, and then mangled. Occasionally, the group in question is actually greek (as in frat) but more often, it is asian students.

    Thats what this example looks like. A snippet of code that almost calculates ten factorial - modified incorrectly somehow. The student will go to the wall insisting that it calculates a factorial and cry over the great injustice.

    In fact, I was once called before the dean and student advocate to defend the failings and the students' "defense" (laughably) was that the code in the programming assignment was copied directly from some text book and so must be correct. Nevermind that it was 1) not copied correctly, 2) did not fulfill the requirements of the assignment completely and 3) was plagarized.

    My experience, my opinion. There are, of course, plenty of unqualified American programmers. Most of them specialize in Java.

  • American Programmer (unregistered) in reply to Michael
    As regards working as a team, teamwork is one of the most sought after properties of programmers in the business world.

    Ordinarily, I agree with you. But if you've never written the factorial function yourself and simply had a team member work it out and then turned in his work - then you still don't know how to write a factorial function, do you?

    School is not the business world. The goals are different. The point is not to get a factorial function written. The point is to impart the knowledge to each and every student how to write one. Working in teams prevents attainment of the goal.

    Sheesh.

  • (cs) in reply to American Programmer
    American Programmer:
    There are, of course, plenty of unqualified American programmers. Most of them specialize in Java.

    And you not only specialize in it, thats what you teach, am I correct?

    ducks and covers

    Seriously, if you are going to qualify your statements, don't do so by making another overly general, and just as incorrect one while doing so. It makes your qualification of statements so ineffectual.

    We could easily discount anything you say if we truly believed the following: Those who can, do. Those who can't, teach.

  • (cs) in reply to American Programmer
    American Programmer:
    As regards working as a team, teamwork is one of the most sought after properties of programmers in the business world.

    Ordinarily, I agree with you. But if you've never written the factorial function yourself and simply had a team member work it out and then turned in his work - then you still don't know how to write a factorial function, do you?

    School is not the business world. The goals are different. The point is not to get a factorial function written. The point is to impart the knowledge to each and every student how to write one. Working in teams prevents attainment of the goal.

    Sheesh.

    Working in teams could accelerate that goal. If one member has a eureka moment he can share that with the rest thereby each member of that team gets the benefit of an individuals ideas. It all depends on the dynamics of the team and how dedicated they are to actually learning. The team idea isn't at fault here, it is the individuals that make up that team.

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

    Nice code. Will never return though...

    Captcha: alarm - what this code raised internally (in me)

    Sure, it's calling factorial(n) rather than factorial(n-1) on recursion. Is this a typo, or a real error? This high school student at least understands what recursion is.

    A high school student has time to learn the pitfalls. A CS grad interviewee should know all this!

    I'd test recursion with these questions: What is recursion? How do you write a factorial function with recursion? Where is the recursion in factorial? (*) Why is this recursive factorial function a bad way to do it?

  • (cs) in reply to kirchhoff
    kirchhoff:
    bstorer:
    On a related note, does anyone want to solve for z in G(z) = 12 where G is the Gamma function? Because that's like a factorial.

    There's no easy solution other than Newton's method using series approximations for gamma and digamma. Nor is there a most-complex-domain-converging series-like expression that I can find, like there is for the gamma function itself.

    Like, you can solve for the limit of the upper and/or lower incomplete gammas through the inverse of regularized gamma. (Regularized gamma is G(a,z)/G(a) with parameters a and z) But it only solves for the 'z' parameter in G(a,z)/G(a), not the 'a' parameter. But in general you can't solve for 'a' in G(a) (imagine 'G' is the greek gamma symbol).

    And now you know why I wanted someone else to do the legwork.

  • (cs) in reply to Andrew
    Andrew:
    I'd test recursion with these questions: What is recursion? How do you write a factorial function with recursion? Where is the recursion in factorial? (*) Why is this recursive factorial function a bad way to do it?

    Nice, this actually promotes a two way dialog. Something missing in many interviews. You interviewing any time soon?

  • American Programmer (unregistered) in reply to KattMan
    KattMan:
    Those who can, do. Those who can't, teach.

    Those who can do both - teach night school as adjunct faculty.

  • American Programmer (unregistered) in reply to 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.

    I've found a good similar question is "What is an abstract base class and why would I want one?"

    Precious few developers can answer that question coherently.

  • (cs) in reply to American Programmer
    American Programmer:
    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.

    I've found a good similar question is "What is an abstract base class and why would I want one?"

    Precious few developers can answer that question coherently.

    Let me give that a shot.

    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?

  • Tim (unregistered) in reply to Welbog

    http://xkcd.com/c221.html

  • kibbles (unregistered)
    Faxmachinen:
    I'm amazed at the amount of ways in which you guys have managed to break or mangle the factorial function.

    im more amazed by the apparent indignation of the posters -- as if their mere prior memorization of these terms and riddle somehow meant they were on par w/ having devised them. ridiculous.

    myself, id never heard of factorials or recursives, and ive been doing enterprise coding for 8 years for a variety of fortune 100 clients. granted, i use recurisve patterns, just hadnt known its label. never heard of nor used factorials.. but then, i never took a comsci class, either.

    my point? for many/most, perhaps textbook comsci lessons arent so valuable in the Real World after all...

  • C (unregistered)

    True... a poor answer. But what a daft question to ask.

  • bill (unregistered) in reply to KattMan
    KattMan:
    American Programmer:
    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.

    I've found a good similar question is "What is an abstract base class and why would I want one?"

    Precious few developers can answer that question coherently.

    Let me give that a shot.

    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.

  • CS Student Who Doesn't Want to Be a Dummy (unregistered)

    So here's my attempt at writing the recursive method:

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

    Please be kind about the Java, I'm just learning. Gentle corrections would be most appreciated.

  • gygax (unregistered) in reply to operagost
    operagost:
    unklegwar:
    Joseph:
    I just find it amazing that people who code like that can actually graduate!

    Garbage In - Garbage Out

    I sat behind a girl in my Comp Sci classes who declared to the entire class that multiplying a positive number by a negative number yielded a positive number.

    That reminds me of the "Time cube" guy, who says that the product of two negative numbers being positive is "wrong and stupid."

    Not to mention he thinks cubes have 4 corners, not 8.

  • Southern (unregistered)

    You know nothing. The factorial of any given (integer) number is 42. It doesn't matter if it's not positive any more either, neither if it'll fit on an 'int' variable.

    Revolution!

  • Anonymous (unregistered)

    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?

  • Rugged individualist (unregistered)

    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.

  • Jon (unregistered) in reply to Longtime C guy
    Longtime C guy:
    The python version:
    def factorial(n) :
    	return (1 if n <= 1 else reduce (lambda x, y : x * y, range(1, n + 1)))
    I prefer:
    def factorial(n):
            return reduce(operator.mul, range(1, n + 1), 1)

    Or, for bonus points:

    factorial = (lambda f: lambda n: 1 if n <= 1 else n*f(f)(n-1))(lambda f: lambda n: 1 if n <= 1 else n*f(f)(n-1))
    PseudoNoise:
    Jason:
    C++

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

    pfff, that's not C++.

    (template metaprogramming snipped)

    Screw that; use a smart language:

    (defun factorial (n)
      (if (<= n 1) 1 (* n (factorial (1- n)))))
    
    (factorial 10) ; compute factorial of 10 at runtime
    #.(factorial 10) ; compute factorial of 10 at compile time
  • (cs) in reply to Anon
    Anon:
    Anon:
    gwenhwyfaer:
    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 actually an excellent way to describe OO programming... Probably quoted from a book, but very easy to understand..

    (emphasis mine) Actually not - I made it up on the fly. But I suppose I should take your speculation as a compliment? If so, thank you.

  • (cs) in reply to Random832
    Random832:
    When I respond to just one statement, I don't always copy the whole thing, and I don't always read the parts i'm not copying.
    Really, now...?
  • American Programmer (unregistered) in reply to bill
    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.

  • American Programmer (unregistered) in reply to Jon
    Jon:
    ]Screw that; use a smart language:
    (defun factorial (n)
      (if (<= n 1) 1 (* n (factorial (1- n)))))
    
    (factorial 10) ; compute factorial of 10 at runtime
    #.(factorial 10) ; compute factorial of 10 at compile time

    OK - BTW nobody did any error handling at all.

    factorial
    
       self < 0 ifTrue: [self error: 'Factorial undefined on negative numbers'].
       ^self = 0 
          ifTrue: [1]
          ifFalse: [self * ((self -1) factorial)]
    
  • Bob (unregistered) in reply to pitchingchris

    No, I don't know anyone who was ever this dumb. Certainly not me.

  • poopie d. (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.

    In a strongly typed language, this helps enforce "interchangable" polymorphism, since all subclass methods implementing an abstract method must return the same type of object.

    Sounds like bondage and discipline to me. I'll stick to Ruby.

  • (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.

    42 ?

  • Mike (unregistered) in reply to Fj_
    Fj_:
    LOL WTF?

    It actually returns 13, because 12 is incremented one last time before the comparison.

    The return value is really 12, but the loop ends because i is 13. The 'a' variable captures the value of i before it's incremented and then tested by the for loop.

    Here's my code snippet...Just because I like writing fun little code snippets:

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

    Self nit-pick 1: Doesn't check for negative values. Self nit-pick 2: Does one more call than it needs to.

  • Anon (unregistered)

    "What is an abstract base class and why would I want one?"

    I'd love to know the "expert" answer to this one. If you want to specify required behavior, use an interface. An abstract base class takes away flexibility and gives you what exactly, other then a bigger object hierarchy?

  • not a programer... (unregistered)

    How did this get so many hits?? Do you programers find this funny/tragic?

  • Phlip (unregistered) in reply to Guru Buckaroo
    Guru Buckaroo:
    What you have all failed to notice, is that this function WILL return, immediately, the value it is called with. After all, that first if is using an assignment operator, not a comparison operator.

    'course, it won't compile.... but who's perfect...

    Huh? It'll infinitely recurse even if that is an assignment operator... it'll set n to 0, which evaluates to false, so it'll return 0 * factorial(0) which'll do the whole thing all over again.

  • American Programmer (unregistered) in reply to Anon
    Anon:
    "What is an abstract base class and why would I want one?"

    I'd love to know the "expert" answer to this one. If you want to specify required behavior, use an interface. An abstract base class takes away flexibility and gives you what exactly, other then a bigger object hierarchy?

    Spoken like a true 'java programmer'.

    There are some universal motivations. An abstract base class often embodies a concept or classification, along with a protocol that is unique to that concept. In this case it is a kind of documentation - clarifying intent and reducing the number of concepts - which provides a certain reduction in complexity for the developer at some level as he can generally ignore the details of the subclasses below. An interface also fills this role (assuming your language has interfaces).

    The reason for choosing an abstract base class over an interface is primarily to share common code. If there is code that is likely to be reproduced over and over again, then it is worthwhile to move the code up the hierarchy to an abstract base class where it can be shared more conveniently. There are drawbacks to this like if your language does not support multiple inheritance and you really need to mix a couple of concepts into one class. At that point, you should have the abstract base class implement an interface and write everything in terms of that interface. You'll likely have to duplicate a bunch of code. That's life.

    In statically typed langages there is an additional reason. It enables polymorphism and substitutability. (lookup Liskov Substitution Principle). Without an abstract base class, you cannot implement polymorphism. (technically, the base class need not be truly 'abstract' but it is not generally good form to derive from concrete base classes).

  • code guy (unregistered) in reply to Lee
    Lee:
    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!!

    Assignment statements evaluate to the value of the assignment. This is why tricks like

    while (c = getc() != EOF)

    work. n = 0 evaluates to 0, so it is false.

  • (cs)

    Okay. Who's the spy?

    I can confirm that this is a true story, because I was the one interviewing the candidate. I recognize the code, even though the story is slightly different (thanks, Alex!) I had to switch to the factorial problem, because when I asked him to convert an integer to a string using any language he wanted -- event pseudo-code! -- he said "I don't know" after writing three lines. 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.

  • BillyBob (unregistered) in reply to iMalc

    When someone asks:

    Article:
    Richard: Could you write a quick function that will find the factorial of any given number using recursion?

    and you reply with:

    iMalc:
    Hmm, I would have asked whether he wanted the recursive, iterative, lookup table, or compile-time template meta-programing version.

    I'd say you could pretty much get up and walk out the interview right at that point.

  • (cs) in reply to ashton
    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!
  • (cs)

    const unsigned int factorial(const unsigned int n) { return n? n * factorial(n - 1): 1; }

    I rather don't get it why all you C++ coders don't use the nice unsigned int types and bitch around arguing about how to handle the negative. </rant>

Leave a comment on “F'd Factorial”

Log In or post as a guest

Replying to comment #:

« Return to Article