• ctd (unregistered)
    M: I'd Google for John Carmack's formula to calculate it.

    That the interviewee knew of that solution is a good sign. That the interviewer did not, it seems, know of that solution is a bad sign.

  • Kasper (unregistered)

    I have interviewed more than 100 people, and I have come across a few with an attitude like snoofle. With such candidates, I'd recommend that we did not hire them, because of their attitude.

    Of course programmers are not supposed to reinvent square root every time they need to calculate it. But somebody has to implement it in the first place. And whenever new platforms are put into use, there are some pieces of basic code that has to be written over again. So there is actually a need for people who can write those basic pieces of code again.

    But that's not the point in asking such a question. The point surely was to test the candidates ability to write some code to solve a simple problem.

    The interviewer learned three things about snoofle from that question:

    1. He doesn't know any of the many possible algorithms to solve this problem.
    2. He doesn't have the skills to derive an algorithm from scratch to solve a quite simple problem.
    3. He displays a bad attitude when faced with a task he doesn't like.

    Given how much the interviewer learned about the candidate from that one question, I think it was a great question.

  • raboof (unregistered)

    Situations like the third example always reminds me of the literal meaning of 'intelligent'.

    'Intelligent', from the latin verb, roughly means 'he who understands'.

    This means to answer a question intelligently, you should not just take the question and find an answer that matches it, but understand why it is asked, and what the interviewer is actually trying to learn.

    "Use the language API function" is a great first answer to that question. From the follow-up questions, however, it should be fairly obvious that the interviewer wants to see how the interviewee approaches a problem independently.

    sqrt is a fairly good example problem to test this with: the problem is easily and clearly defined and there's a couple of solutions anyone should be able to invent on-the-spot. In practice of course the problems you'll have to be able to independently solve are not sqrt, but domain-specific problems - however, explaining a foreign domain first would distract from the point of the excercise, hence a well-known problem like sqrt is better suited to test this ability. Even a 'wrong' answer can be an acceptable one, especially when you can refine it after getting feedback on it.

    Inferring that because the interviewer asks this question, developers at this company will always be forbidden to use google or other reference material, is ludicrous and anyone who does this deserves unemployment.

    Next time, be intelligent, and answer the question the interviewer is trying to ask, not the one he is actually asking.

  • Sam I am (unregistered)

    As far as that last one goes the interviewer could probably have come out and initially asked to "come up with an algorithm to calculate a square root", but beyond that, there really wasn't much else to do.

    even after the first couple "google it" responses, the interviewee should have gotten a clue by then.

    "snoofle" didn't even appear to allow the interviewer to lead him a little bit.

    If the interviewee wasn't referred to as "me" so many times, I'd think that he was the WTF

  • OccupyWallStreet (unregistered) in reply to foo
    foo:
    emaNrouY-Here:
    TheRider:
    Niels:
    An iterative approximation for a square root shouldn't be hard to come up with. <SNIP>
    What if you can't use the multiplication operator to square a number?
    And What if you can't use addition?

    (It's a flipping adding machine!!!)

    If you need anything more than NAND gates, you're not qualified.

    What if you're not allowed to use NAND gates? And no, wiring transistors up to form NAND gates is not allowed. You are, however, free to wire up transistors to form any other logic gate (except NAND), but the gate you choose is the only one you can use.

  • (cs)

    For the interviewer in "...Stupid":

    for (i=0; (i*i) <= n; i++); i--;

    Submitted on the theory that the interviewer doesn't know "sensible algorithm" from beans anyway. Especially since I can show exact result for a cherry-picked input of, say, 64.

    (Trust me to also carefully point out how elegant this one-liner is...)

    Oh, BTW, haven't we seen this interviewer before? Right here in TDWTF?

    Addendum (2012-09-19 20:57): Well, maybe. I think he's either interviewer or maybe the interviewee (not sure which) from "Riddled", A Most Wonderful Opportunity, Multiple Frustrations, and More.

    I thought it sounded familiar.

  • chris (unregistered) in reply to Niels

    that, or 2^(1/2)

  • (cs) in reply to ctd
    ctd:
    I'll second Nagesh's comment.

    I don't give a damn what he said - this the real WTF.

  • (cs) in reply to Anoldhacker
    Anoldhacker:
    Niels:
    An iterative approximation for a square root shouldn't be hard to come up with.
    private static double EPSILON = 0.00001;
    public static double sqrt(double x)
    {
      if (x <= EPSILON) return 0; // should error
      double lower = 0, upper = x;
      while (upper - lower > EPSILON)
      {
        double guess = (upper - lower) / 2;
        if (guess * guess > x)
          lower = guess;
        else
          upper = guess;
      }
      return lower;
    }

    This should be considered a good example of precisely why you don't do things like this yourself. The square root of x for small x is much larger than x. The quick return is not needed for non-negative numbers, and if it were, the boundary would be EPSILON * EPSILON. (And no, the square root of -1.0 is NOT even close to 0.0.)

    Yes, my degrees are in mathematics, and I did floating point validation in the '90s. Seriously, don't try this at home, kids.

    (The way that we actually compute floating point square roots is fun. We look up the first several digits for the inverse square root, and then refine it based on polynomials designed to cancel the error term, usually quadratically. Once there is enough precision, you multiply back the original value to get the square root. Yes, you want a real proof that the algorithm works.)

    Clearly Anoldhacker, you were a Discrete Mathematician. All REAL Mathematicians know root(x)=root(x) and that's the end of it. Just like pi = pi. None of this 3.1415... blasphemy.

  • Pete (unregistered) in reply to ¯\(°_o)/¯ I DUNNO LOL
    ¯\(°_o)/¯ I DUNNO LOL:
    For those who still don't see the WTFery of the square root thing, how about this. A guy is interviewing to be a carpenter.

    Interviewer: If you had to put two pieces of wood together, how would you do it? Carpenter: I guess I could nail them together, or maybe glue. I: But what if you didn't have any nails or glue? C: I'd go out to Home-O-Rama and buy some. I: But what if there was no Home-O-Rama? C: Then I'd go to a hardware store. I: But what if there were no such thing as nails or glue? How would you make them? C: Can I have some of what you're smoking?

    Yeah, maybe he could have come up with a different question, but using square root as the subject was like asking a carpenter how he would make nails if they hadn't been invented yet.

    Besides, how many of you even use square roots in your day-to-day work? I've been programming for decades and never had to do something that used square roots.

    The whole point of a simplified toy examples is to allow to see the problem solving approach of candidates within a short interview.

    Asking a carpenter how he would make a glueless joint for two pieces of wood is a natural question - it's not done in "production" nowadays since glue is usually simpler and sturdier, but any reasonable professional carpenter should either know or figure it out in 5 minutes.

    Asking a programmer in how he would reimplement a simple function from scratch is a natural question - it's not commonly done in production, but any reasonable programmer should know or be able to figure it out in 5 minutes. Asking to build a more complex function than sqrt (one that wouldn't be in libraries) would simply require more time to see the same effect.

    The exam showed: Candidate is able to reimplement well known techniques by looking up the details in a reference book or internet. Candidate is unable or unwilling to develop solutions independently even when requested to do so.

  • wizofaus (unregistered) in reply to Spewin Coffee

    Working out (or at least, approximating) the square root of a number is a pretty basic exercise in recursive programming though - I'd be a bit concerned by a programmer that would give up that easily.

  • Enrique (unregistered) in reply to raboof
    raboof:
    Inferring that because the interviewer asks this question, developers at this company will always be forbidden to use google or other reference material, is ludicrous and anyone who does this deserves unemployment.

    I have seen a couple of companies whose developers didn't have access to internet or books, so it is not unreasonable to infer that. Also, I remember one company where you couldn't use JOINs in stored procedures. There are many WTF companies out there. English is not my native language, sorry for any mistakes.

  • Sam I am (unregistered)

    snoofle should feel a little bit silly when writing that diatribe about being asked to approximate the square root, and later reading a comments section where half the people knew how to come up with the answer.

  • (cs)

    Are there any real programming languages without a square root function? I don't mean toy languages, I mean those in actual production use.

    I was thinking back over my programming history to see if I could spot one, and everything back to Applesoft Basic from the late 1970's on a 1 MHz 8-bit CPU had a square root implementation. Languages I learned later but which are older (C, Pascal, etc.) have had it from the beginning, too.

    What I'm trying to get at is, is the interviewer's question anything more than an impossible hypothetical? Never mind that the context was Java. Is there even a snowball's chance someone would be required to do this?

    Riffing on snowballs, here's a new hypothetical:

    You're in Antarctica, a blizzard is blocking the satellite uplink to the Internet, and you have to fix a bug in an embedded system or Dooooom happens. The bug must be fixed in the next 2 hours, and the blizzard is expected to last another day. The embedded system is an 8-bit microcontroller with a toolchain you've never used before, but it uses a well-known programming language, and you have complete reference manuals for the toolchain and the language. You have no other reference material. It turns out that the bug fix requires a square root operation. The language entirely lacks what we'd call a math library today: so, no raising the number to a half power, no trickery with logarithms. You have to build the sqrt() implementation using nothing more than sixth-grade arithmetic.

    Is that also an impossible hypothetical?

  • (cs) in reply to TheRider
    TheRider:
    Niels:
    An iterative approximation for a square root shouldn't be hard to come up with.
    private static double EPSILON = 0.00001;
    public static double sqrt(double x)
    {
      if (x <= EPSILON) return 0; // should error
      double lower = 0, upper = x;
      while (upper - lower > EPSILON)
      {
        double guess = (upper - lower) / 2;
        if (guess * guess > x)
          lower = guess;
        else
          upper = guess;
      }
      return lower;
    }
    What if you can't use the multiplication operator to square a number?

    No multiplication? Multiplication "expensive"?

    Use the "odd integer method" with proper scaling. I know of one computer system that did it that way.

    Of course, you could always use n^(0.5) which also works.

    If all else fails, try a slide rule!

  • (cs) in reply to herby
    herby:
    No multiplication? Multiplication "expensive"?
    Sure. A great many 8-bit CPUs (and microcontrollers) lack a hardware multiplier. High level languages for such systems typically provide a software multiplication implementation, but if it's general-purpose, its going to be hundreds of instructions long. If you're writing in assembly, you get to write (or swipe) the implementation yourself.

    Even on systems with a hardware multiplier, multiplication may take many cycles, whereas an integer addition is typically the fastest sort of instruction.

    You might not be aware of it, but there are still — today — more 8-bit CPUs sold than any other, by volume. There's even new code being written for 4-bit CPUs.

    Here's such a CPU, still being sold, though Atmel recommends against using it in new designs. It's a 4-bit CPU with an instruction set optimized for a dialect of Forth. No hardware multiply instruction. The programming manual claims there is a software multiplier at the qForth level, but more reading suggests the only thing that actually works is 2* which is implemented in software as a shift-left operation.

    I guess this answers my question above, but I'd still appreciate more answers.

  • (cs) in reply to Kasper
    Kasper:
    I have interviewed more than 100 people, and I have come across a few with an attitude like snoofle. With such candidates, I'd recommend that we did not hire them, because of their attitude.
    Sadly, most of you still seem to be missing the entire point, so let me illustrate...

    Hypothetically, you are the interviewer, I am the candidate, and for the sake of argument, I am Mr. Math Wizard. You ask your question (in an intelligent way): We'd like to see how you think and go about problem solving; please explain how you might go about designing a method to compute a square root. As a shrewd interviewee, I ponder for a second, then respond with iterative approximation, perhaps mentioning some edge cases, negative numbers, numbers < 1, etc.

    You probably think to yourself: Hey, this guy knows his stuff, and will probably use that as a significant portion of your hiring decision.

    Epic Fail.

    The only thing you have learned about me is if I can come up with a way to compute a square root. Unless the job entails figuring out new mathematical algorithms, or computing square roots, you have learned absolutely nothing about my ability to do the actual job.

    It's actually worse than that, because you now have a false sense of positive security that I am a good fit. I may or may not actually be a good fit, but you don't know that based upon your question.

    I, OTOH, know that you have chosen a question that fails to give you the sole piece of information it was designed to detect: Can I think?

    In fact, that is not the complete question you wanted to answer. What you wanted to know was: Can he think in a way that helps him accomplish what we want to hire somebody to do?

    A good question along those lines is: Our production environment looks like x. Every now and then, y happens with symptoms a, b and c. Given limited knowledge of the details, how might you go about diagnosing the problem and how might you proceed to solve it? This tells you whether I can think AND if I know how to do the job.

    It's not that I have an attitude about answering questions; I get it; you have to play nice to get the job. It's just that I've learned over the decades that certain types of questions are red flags, and depending upon the tone/manner with which they are posed, I may play along, or just accept it as a wasted trip and leave - because some jobs just aren't worth having.

  • consequat (unregistered) in reply to coder guy
    coder guy:
    It seems to me that anyone who can't even come up with a lame attempt at successive approximation to figure out a square root without running to a reference isn't fit for a programming job.

    And I think that anyone who's wasting time to unnecessarily disassemble anything is a time waster and probably a bullshit programmer, too.

  • consequat (unregistered) in reply to DES
    DES:
    If I was conducting interviews for a programmer position, I'd immediately fail any candidate who didn't know Newton's method and was unable to come up with it (or a similar successive approximation method) on the spot. It is blindingly obvious, and trivial to implement.

    I'd probably also fail any candidate who didn't, at some point, suggest Math.exp(Math.log(x) / 2). And even if Math.log() isn't available, you can easily compute a rough lower bound of log(x) through successive division, as an initial guess for successive approximation.

    (to those who complained that Newton's method does not give an exact value: where does it say that the interviewer expected an exact value? in any case, with a few exceptions, the floating-point representation of a number will always be an approximation of the actual value.)

    As for Carmack's method: assuming it can be implemented in Java (it can't—not without a lot of contortions), it can easily be derived from first principles if you know basic algebra and the layout of IEEE 754 floating-point numbers. If you don't know the layout, you can easily figure it out by looking at the binary representation of a handful of test values.

    So TRWTF is that the candidate refused to even try to think of an answer, then blamed the interviewer for asking him a question he should have been able to answer but wasn't.

    You're a heavy unit-test guy, aren't you?

  • consequat (unregistered) in reply to StMarc
    StMarc:
    Perhaps he wanted to know if that last fellow knew anything about how algorithms are actually *created.* Since anybody who knows what a square root actually *is* should be able to create an algorithm to approximate one to any desired precision in about ten seconds.

    I'll give you my salary for a month if you even copy it from another piece of paper in 10 seconds, let alone come up with even relatively accurate solution without anticipation or prior practice.

    In other words, you're a dumbass.

  • consequat (unregistered) in reply to Sockatume
    Sockatume:
    The interviewer doesn't want to know how the candidate *thinks* he would react to a problem outside of his training. The interviewer wants to know how the candidate would *actually* react. Apparently in this case it's to rage out of the office.

    I'd love to see his take on the Kobiyashi Maru.

    ("Interview 2.0"? Problems like that have been a standard part of technical interviews for decades.)

    No, dude - the interviewer is a plain old dumbass with no good intention at all. He simply couldn't think of any other good-quality question, so he thought of going down th what-if route. My child often does this to me, and the interviewer probably hasn't advanced much from that age.

  • foo (unregistered) in reply to OccupyWallStreet
    OccupyWallStreet:
    foo:
    emaNrouY-Here:
    TheRider:
    Niels:
    An iterative approximation for a square root shouldn't be hard to come up with. <SNIP>
    What if you can't use the multiplication operator to square a number?
    And What if you can't use addition?

    (It's a flipping adding machine!!!)

    If you need anything more than NAND gates, you're not qualified.

    What if you're not allowed to use NAND gates? And no, wiring transistors up to form NAND gates is not allowed. You are, however, free to wire up transistors to form any other logic gate (except NAND), but the gate you choose is the only one you can use.

    That's neither funny nor relevant.

  • derp (unregistered) in reply to snoofle

    The interviewer in #3, in my mind, was looking for snoofle to implement a function that could compute the square root. The fact that he was unable to communicate that very simple requirement to his interviewee puts the WTF ball in his court. There is no inherent problem with asking someone to implement their own sqrt function, it's simply that it was not asked properly.

    I would not like to work for such a person either, because I would much rather work for someone who has the ability to make their expectations and needs clear.

  • Mark (unregistered) in reply to asdbsd

    Yes, being able to solve something on your own is a useful skill, but really, the interviewer should have framed the problem more clearly, stating that was what was expected, instead of inventing hypothetical "what if" scenarios that aren't ever going to happen.

  • Mark (unregistered) in reply to DES

    Uhmmm.... I'd like to see you use newton's method to calculate the square root of a number without having access to the square root function.

    It probably doesn't help matters that the first derivative of sqrt(x) contains a square root.

    While yes, one can argue that the interviewer was almost certainly asking the person to describe how they would personally approach solving a new problem that they hadn't had to solve before, it would have probably been better if this particular question had been framed very differently, and the expectation that the interviewee should take some time to think about it had been clarified up front, instead of adding all these highly contrived "what ifs" after the question had already been posed, and an answer given.

  • SQRT (unregistered) in reply to snoofle
    snoofle:
    Kasper:
    I have interviewed more than 100 people, and I have come across a few with an attitude like snoofle. With such candidates, I'd recommend that we did not hire them, because of their attitude.
    Sadly, most of you still seem to be missing the entire point, so let me illustrate...

    Hypothetically, you are the interviewer, I am the candidate, and for the sake of argument, I am Mr. Math Wizard. You ask your question (in an intelligent way): We'd like to see how you think and go about problem solving; please explain how you might go about designing a method to compute a square root. As a shrewd interviewee, I ponder for a second, then respond with iterative approximation, perhaps mentioning some edge cases, negative numbers, numbers < 1, etc.

    You probably think to yourself: Hey, this guy knows his stuff, and will probably use that as a significant portion of your hiring decision.

    Epic Fail.

    The only thing you have learned about me is if I can come up with a way to compute a square root. Unless the job entails figuring out new mathematical algorithms, or computing square roots, you have learned absolutely nothing about my ability to do the actual job. <snip>

    I respectfully submit that you are also missing the point. I fall in the camp that thinks this is a reasonable interview question. I might consider using it in the future.

    Your assumption that I would think "Hey, this guy knows his stuff, and will probably use that as a significant portion of your hiring decision" would be wrong. It's only 1 question. You don't know that the next question wouldn't have started with 'Our production environment looks like x...'. You judged the interviewer based on 1 question. I judge an interviewee based on answers to multiple questions.

    I even like the approach the guy used of pulling the rug out from under you as you give the right answers. It's actually better than jumping straight to write a sqrt function from scratch.

    Here's what would go through my mind as the interviewer in that scenario: Interviewer: How would you calculate a square root (java)? Me: Math.sqrt(double) +5 for knowing the obvious solution without having to look it up. I: What if there were no square root function? M: I'd Google for John Carmack's formula to calculate it. +20 for being able to name an existing algorithm to solve the problem. +10 for knowing that Google is your friend here. +10 for knowing that this is a solved problem, no need to reinvent the wheel here. I: What if you couldn't use Google? M: Assuming you mean no access to the internet, since I don't happen to know how to calculate a square root, I'd ask someone... +10 for not being afraid to ask someone when you don't know the answer, rather than wasting hours trying to figure it out yourself. I: What if there were nobody to ask? M: I'm not a math whiz; I'd drive to a bookstore and get a book on how to do it. +5 for admitting you don't know everything. +5 for remembering that there were bookstores before there was Google. I: What if there were no bookstore? M: Ok, so you want me to come up with a formula I've told you I don't know, in the next 10 seconds, without access to any of the usual reference sources? Yes, I would like you to come up with an algorithm to solve the problem, even if it isn't a very good one. Take as much time as you would like. There is no 10 second time limit. Think about it while I check my email. Take your time. Use the whiteboard if you want.

    M: <Walks Out> -1000. Too bad. He was doing fine at +65. But hiring this guy would have been an Epic Fail. When faced with a difficult challenge, he chooses flight over fight. Not what we need here.

  • Norman Diamond (unregistered) in reply to Joe
    Joe:
    I've been programming for 30 years and I can guarantee you I've never had the slightest use for Math.exp or Math.log. [...] And I'm talking real code, not drag-and-drop crap.
    I've been programming for longer, so I HAVE had use for exp2 and log2. Once. In a device driver. The Linux kernel for x86 had some macros that could be used before and after floating point calculations so they could be used safely in a driver. The Linux kernel for other architectures didn't, so I had to convert my code to use lookup tables instead of calculating how much power to apply to the antenna.

    I have a feeling programmers at NASA, Spar, and maybe oil companies use those functions more.

  • derp (unregistered) in reply to SQRT
    SQRT:
    I even like the approach the guy used of pulling the rug out from under you as you give the right answers. It's actually better than jumping straight to write a sqrt function from scratch.

    I: What if there were no bookstore? M: Ok, so you want me to come up with a formula I've told you I don't know, in the next 10 seconds, without access to any of the usual reference sources? Yes, I would like you to come up with an algorithm to solve the problem, even if it isn't a very good one. Take as much time as you would like. There is no 10 second time limit. Think about it while I check my email. Take your time. Use the whiteboard if you want.

    Then you should just say "please give me a function" somewhere and totally sidestep this bullshit. It's the obvious and easy thing to do as an interviewer. YOU have to make your expectations clear so then it falls upon them to rise to meet them.

  • foo (unregistered) in reply to Mark
    Mark:
    Uhmmm.... I'd like to see you use newton's method to calculate the square root of a number without having access to the square root function.

    It probably doesn't help matters that the first derivative of sqrt(x) contains a square root.

    While yes, one can argue that the interviewer was almost certainly asking the person to describe how they would personally approach solving a new problem that they hadn't had to solve before, it would have probably been better if this particular question had been framed very differently, and the expectation that the interviewee should take some time to think about it had been clarified up front, instead of adding all these highly contrived "what ifs" after the question had already been posed, and an answer given.

    Yeah, what if Google actually existed and told you how to use Newton's method to calculate the square root? Nice try.

  • foo (unregistered) in reply to Norman Diamond
    Norman Diamond:
    Joe:
    I've been programming for 30 years and I can guarantee you I've never had the slightest use for Math.exp or Math.log. [...] And I'm talking real code, not drag-and-drop crap.
    I've been programming for longer, so I HAVE had use for exp2 and log2. Once. In a device driver. The Linux kernel for x86 had some macros that could be used before and after floating point calculations so they could be used safely in a driver. The Linux kernel for other architectures didn't, so I had to convert my code to use lookup tables instead of calculating how much power to apply to the antenna.

    I have a feeling programmers at NASA, Spar, and maybe oil companies use those functions more.

    I don't work at any of those, yet I occasionally need math functions, sometimes for simple tasks such as laying out items in a 2D grid regularly with correct aspect ratio (integer sqrt, round-up). And I'm talking cheap desktop crap, not real code (graphics, sound, real-time device control) where these functions occur a lot more, obviously (and which fortunately makes up most of my work).

  • Mark (unregistered) in reply to foo
    foo:
    Yeah, what if Google actually existed and told you how to use Newton's method to calculate the square root? Nice try.
    My bad... I was thinking of Newton's method being used to calculate zeros of the square root function itself (which actually isn't even useful... I feel foolish for even bringing it up), rather than finding the zero's of the inverse function, which of course is x^2, and offsetting it by the value whose square root you want.

    Although my main point still stands. It would have been better if the interviewer had framed the question more clearly with respect to what he was expecting.

  • Lee (unregistered)

    I was invited to interview for a position on the security team of a major website. In preparation, I ran some tools I've written to do some benign reconnaissance. Nothing illegal or harmful, just the types of requests a search engine like google would perform, coupled with my specialized knowledge of what to look for.

    I arrived prepared to tell them "It looks like you might have trouble here and here, and I propose this and this to cover yourselves while you fix it like this."

    Instead, the interviewer wanted me to write some code to calculate prime numbers on the whiteboard.

    So, now, they've hired their submissive puzzle solver, and I have a handful of vulnerabilities -- still not fixed -- that give me access to a major slice of e-commerce. Guess who (potentially) wins?

  • JustSomeGuy (unregistered) in reply to asdbsd
    asdbsd:
    snoofle:
    Why? The guy wanted an exact value, not an approximation.

    If I asked you to come up with a formula for something you honestly didn't know how to calculate, you might approximate, but you won't get it exact.

    Just to remind you, there's no such thing as "exact" with floating point numbers. So they didn't ask him to give "exact" value. They asked to do his best at approximation.

    And, just to remind you, there is such a thing as exact with floating point numbers. IEEE754 can represent negative-powers of two quite nicely thank you very much. Things like 1/2, 1/4, 1/64 or any number that can be represented by summations of those (within the bounds of the bits available) are, to all intents and purposes, exactly representable.

    It's only when you get outside the bounds of precision, or have a number like 0.1 which can't be represented as sums of 2^(-whatever).

    Don't be a pedant on the net. There are so many of us around :-)

  • JustSomeGuy (unregistered) in reply to TheRider
    TheRider:
    Niels:
    An iterative approximation for a square root shouldn't be hard to come up with.
    private static double EPSILON = 0.00001;
    public static double sqrt(double x)
    {
      if (x <= EPSILON) return 0; // should error
      double lower = 0, upper = x;
      while (upper - lower > EPSILON)
      {
        double guess = (upper - lower) / 2;
        if (guess * guess > x)
          lower = guess;
        else
          upper = guess;
      }
      return lower;
    }
    What if you can't use the multiplication operator to square a number?

    Use repeated addition? :-)

  • JustSomeGuy (unregistered) in reply to Studley
    Studley:
    What if there were no numbers?

    Then there is no concept of a square root?

  • (cs)

    In some semi-fringe circles of mathematics (Constructivists) an "exact" value of sqrt(2) is nothing more or less than an algorithm which can in principle calculate it to any desired precision.

    Thus to "exactly" calculate sqrt(2), you'd only need to write a class to handle arbitrarily high precision decimal numbers (unless this already exists in Java) and implement your favorite iterative algorithm on it.

  • JustSomeGuy (unregistered) in reply to Anoldhacker
    Anoldhacker:
    Niels:
    An iterative approximation for a square root shouldn't be hard to come up with.
    private static double EPSILON = 0.00001;
    public static double sqrt(double x)
    {
      if (x <= EPSILON) return 0; // should error
      double lower = 0, upper = x;
      while (upper - lower > EPSILON)
      {
        double guess = (upper - lower) / 2;
        if (guess * guess > x)
          lower = guess;
        else
          upper = guess;
      }
      return lower;
    }

    This should be considered a good example of precisely why you don't do things like this yourself. The square root of x for small x is much larger than x. The quick return is not needed for non-negative numbers, and if it were, the boundary would be EPSILON * EPSILON. (And no, the square root of -1.0 is NOT even close to 0.0.)

    Yes, my degrees are in mathematics, and I did floating point validation in the '90s. Seriously, don't try this at home, kids.

    (The way that we actually compute floating point square roots is fun. We look up the first several digits for the inverse square root, and then refine it based on polynomials designed to cancel the error term, usually quadratically. Once there is enough precision, you multiply back the original value to get the square root. Yes, you want a real proof that the algorithm works.)

    So the actual answer should have been "I'd give my mate Anoldhacker" a call and get him in to do the work".

  • SQRT (unregistered) in reply to derp
    derp:
    SQRT:
    I even like the approach the guy used of pulling the rug out from under you as you give the right answers. It's actually better than jumping straight to write a sqrt function from scratch.

    I: What if there were no bookstore? M: Ok, so you want me to come up with a formula I've told you I don't know, in the next 10 seconds, without access to any of the usual reference sources? Yes, I would like you to come up with an algorithm to solve the problem, even if it isn't a very good one. Take as much time as you would like. There is no 10 second time limit. Think about it while I check my email. Take your time. Use the whiteboard if you want.

    Then you should just say "please give me a function" somewhere and totally sidestep this bullshit. It's the obvious and easy thing to do as an interviewer. YOU have to make your expectations clear so then it falls upon them to rise to meet them.

    Yes, I suppose you are right. Because that is how it works in the real world. Your boss always comes to you with requirements that are absolutely clear cut from the start, will never change, have no oddball restrictions, and no bullshit. That's because your boss got the requirements directly from Sales And Marketing, and they obviously always state the requirements clearly from the start. Why wouldn't they? They get the requirements directly from the customer. And not only does the customer know exactly what they want, they are also always right.

    So, yes, you are right. Failing to give the programmer the precise requirements and restrictions from the start is my WTF. One that would never happen in the real world.

    Thank you for pointing that out.

  • JustSomeGuy (unregistered) in reply to robert

    [quote user="robert"][quote user="Anonymous Coward"]1. How do you know he wanted an exact value? You left without offering a non-exact solution.

    1. Successive approximation WILL give you an exact value.

    That's impossible. Most square root functions return an irrational number, i.e.: their digits repeat endlessly without a recurring pattern. There is no representation for the number in a digit-based system.[/quote]

    Rubbish. In base sqrt(2), the square root of two is exactly 1 :-)

  • Roger Garrett (unregistered) in reply to Spewin Coffee

    This is so damn true. I have 40 years experience as a software engineer and in one recent job interview I was told to take a programming test. The "company" consisted of two guys in their early twenties, clearly right out of college, and the test looked like something you'd get from your instructor on Friday for the lessons you'd attended during the week. Just little tidbits of specific elements of a language and to see if you'd recognize the + where a ++ should be. Absolutely nothing about actual software engineering. I got about halfway through the "test" before my frustration got the better of me and I handed it back to them and walked out.

  • Gary Capell (unregistered)

    I would expect any programmer who at least understands what a square root is to be able to come up with at least some binary search approach at approximating a square root.

  • Mike Hunt (unregistered)

    I'm no programmer or maths genius, but I'd have thought you'd guess a number, times it by itself, see if it was greater than or less than the origianl number, refine the guess and iterate that a few times. But that's just me. Here's some dodgy VBA code (as I don't have access to anything else):

    Option Explicit Const ITERATIONS As Integer = 20

    Sub SquareRootBitchez() Dim num As Double Dim i As Integer Dim cntGuess As Double, cntGuessSquared As Double Dim cntMin As Double, cntMax As Double Dim isNeg As Boolean

    num = InputBox("Enter Number")
    If num < 0 Then
        isNeg = True
        num = Abs(num)
    End If
    If num > 1 Then
        cntMin = 1
        cntMax = num
    Else
        cntMin = num
        cntMax = 1
    End If
    
    For i = 1 To ITERATIONS
        cntGuess = (cntMax - cntMin) / 2 + cntMin
        cntGuessSquared = cntGuess * cntGuess
        If cntGuessSquared > num Then
            cntMax = cntGuess
        ElseIf cntGuessSquared < num Then
            cntMin = cntGuess
        Else
            GoTo ExitFor
        End If
    Next
    cntGuess = (cntMax - cntMin) / 2 + cntMin
    

    ExitFor: MsgBox cntGuess & IIf(isNeg, "i", "") & vbCrLf & "After " & i & " iterations" End Sub

  • Mike Hunt (unregistered)

    Ooops... I didn't see the "All Comments" link. I'm probably not the first person to make that point.

    Ignore my last post :P

  • Derp (unregistered) in reply to SQRT
    SQRT:
    derp:
    SQRT:
    I even like the approach the guy used of pulling the rug out from under you as you give the right answers. It's actually better than jumping straight to write a sqrt function from scratch.

    I: What if there were no bookstore? M: Ok, so you want me to come up with a formula I've told you I don't know, in the next 10 seconds, without access to any of the usual reference sources? Yes, I would like you to come up with an algorithm to solve the problem, even if it isn't a very good one. Take as much time as you would like. There is no 10 second time limit. Think about it while I check my email. Take your time. Use the whiteboard if you want.

    Then you should just say "please give me a function" somewhere and totally sidestep this bullshit. It's the obvious and easy thing to do as an interviewer. YOU have to make your expectations clear so then it falls upon them to rise to meet them.

    Yes, I suppose you are right. Because that is how it works in the real world. Your boss always comes to you with requirements that are absolutely clear cut from the start, will never change, have no oddball restrictions, and no bullshit. That's because your boss got the requirements directly from Sales And Marketing, and they obviously always state the requirements clearly from the start. Why wouldn't they? They get the requirements directly from the customer. And not only does the customer know exactly what they want, they are also always right.

    So, yes, you are right. Failing to give the programmer the precise requirements and restrictions from the start is my WTF. One that would never happen in the real world.

    Thank you for pointing that out.

    So thanks for responding to my point by being a smart ass. Let me retort though with a serious response:

    If you're going to deliberately be a shit head when you're interviewing a candidate, then you're only going to hire people who are stupid enough to not see the red flag that you are yet another dumb shit employer.

    Naturally, you're going to get a bunch of tool higher ups that won't give you good requirements. The smart man at least makes sure that he gets as few possible derps like that giving him orders. I don't think it's really strategic from a recruiting perspective to make yourself look like a dumb ass who can't even get his own interview questions straight. That's how you scare the competent people away.

    Derp.

  • (cs) in reply to SQRT
    SQRT:
    Yes, I suppose you are right. Because that is how it works in the real world. Your boss always comes to you with requirements that are absolutely clear cut from the start, will never change, have no oddball restrictions, and no bullshit. That's because your boss got the requirements directly from Sales And Marketing, and they obviously always state the requirements clearly from the start. Why wouldn't they? They get the requirements directly from the customer. And not only does the customer know *exactly* what they want, they are also always right.

    So, yes, you are right. Failing to give the programmer the precise requirements and restrictions from the start is my WTF. One that would never happen in the real world.

    Thank you for pointing that out.

    The point is, if my Boss isn't capable of giving coherent requirements for problems that he's making up himself without going to several iterations, why should I expect that he is going to come up with the requirements for a customers problem correctly? I imagine that Snoofle doesn't want to discover he's been wasting time working on the wrong problem because his boss is an idiot and didn't ask the right questions.

  • Derp (unregistered) in reply to Derp

    Also if I may add, the question in this example is clearly NOT a question where the candidate is supposed to gather requirements. The interviewer wanted a function, but couldn't articulate that desire and instead threw out a bunch of stupid hypotheticals.

    Asking questions that force the candidate into situations where they should try to gather requirements is a great strategy. Is the sqrt question a good way of doing that? I'd say it isn't. So I'm going to say your point is a touch moot and unrelated.

    Unless of course you would use the sqrt question to look for requirement gathering skills, in which case God help you.

  • Anon (unregistered) in reply to Fool
    Fool:
    If I was writing java code and there were no Math.sqrt function i would try to figure out what what jar file is missing, where and then contact IT to fix it.

    This is basically what I did when applying for a support position once with one of those "If you're lost in the woods and mysteriously have absolutely none of the items which people would normally carry into the woods, are then suddenly attacked by a velociraptor, and now need to cross a magma flow with only toothpaste, a ball of twine, and an Eagles 'Greatest Hits' LP..." questions.

    "This question is stupid. What possible reason could I have for being in the woods without any weapons or survival gear?"

  • Konstantin Lopyrev (unregistered)

    The last one is a reasonable question and if you don't know how to do it you shouldn't be hired as a programmer.

  • (cs) in reply to vwiggins
    vwiggins:
    The second one has made me really sad. I get lost all the time, especially if I'm nervous. If someone judged my ability as a developer based on my inability to learn left from right or find my way around a place I've never been before I'd be horrified.
    No, indeed. But i think he was judged by his refusal to do the technical test and fleeing from the area :) I mean he got in touch with Human ressources. Why not just say "er i'm lost in you place" ? I really think the bycicle what juste an excuse to leave when he learned about the written test :)
  • (cs) in reply to JustSomeGuy
    JustSomeGuy:
    In base sqrt(2), the square root of two is exactly 1 :-)
    No, it isn't. 1 in any base is 1; in base sqrt(2), sqrt(2) is of course represented as 10.

    I'd have gone with Newton-Rhaphson as well. But then, I have actually had to use Newton-Rhaphson in my job to derive iterative approximations we can use to solve intractable equations. For what it's worth, I also have to use exp() and log() functions in some of the data modelling I do.

    For reference, I work in the financial industry, and the Newton-Rhaphson stuff comes into play when answering questions like "what is the maximum loan amount you can borrow in this scenario, given that as the loan amount changes a whole lot of other things change which affect your net serviceability amount?" These things are typically implemented by lenders as Excel spreadsheets with a button that calls the Solver (which internally does its own iterative approximation technique), and we have to replicate the results on our in-house system.

    I haven't had to use these things often. But I certainly have had to use them.

Leave a comment on “Trouble With Founders, the Lost Candidate, and More”

Log In or post as a guest

Replying to comment #:

« Return to Article