• (cs) in reply to More
    More:
    No offense. But anybody who writes 14 nested if statements, and don't think: "Surely there must be a better way to do this." is not someone I want to work with.
    Where's your evidence that he didn't think "Surely there must be a better way to do this."? He may well have been thinking that, but didn't know the "better way" off the top of his head and therefore went with the solution that he did know (rather than doing nothing at all).
  • rumpelstiltskin (unregistered)

    A programmer's job is to understand a problem, and then explain it to a machine in a language the machine understands. Why do so many nitwits think it is unreasonable for an interviewer to try to gauge how an applicant goes about the first (and most important) part of his job, trying to understand a problem? If the interviewee did not realize the problem was about prime numbers, then he is most definitely worth less than someone who did. I say that not because I assume the programmer will be using prime numbers in his job, but because I know an educated person is better at understanding problems than an uneducated person. He has seen more types of problems, and he has seen more nuanced problems. And, if you are innumerate, you are just as uneducated as the illiterate.

  • (cs)

    TRWTF is asking for 'ten years experience' in a language that's only been around for thirteen years and has changed a lot.

    Sadly, the reason for this has been mentioned - HR write the ads, and HR don't know about what the company does. It's like the '5 years experience in windows 95' ad posted in 1998.

  • More (unregistered) in reply to JimM
    JimM:
    More:
    No offense. But anybody who writes 14 nested if statements, and don't think: "Surely there must be a better way to do this." is not someone I want to work with.
    Where's your evidence that he didn't think "Surely there must be a better way to do this."? He may well have been thinking that, but didn't know the "better way" off the top of his head and therefore went with the solution that he did know (rather than doing nothing at all).

    Well, anybody who can't think of a better solution is not somebody I'd want to work with either.

    Just imagine having to maintain that person's code shudders

    Captcha: dolor

  • Ebs2002 (unregistered)

    From the original sidebar (that people haven't been reading, it seems)

    Well, in our discussion afterwards I asked him if he could think of any shorter or more efficient ways to write the code. He responded that maybe he would have considered writing a 'while' block to generate the if statements.
    So, yes, the interviewer DID prod him for a more efficient answer.
    The tasks are mostly to check their mathematical ability rather than their programming chops, as the job involves a LOT of mathematical stuff
    Yes, the job involved a LOT of math, so basic high school math principles should be known.
    His code for calculating the Fibonnaci sequence didn't work either - it printed '2' 40,000,000 times
    One of the first algorithms we're taught in college. It's the definitive "Recursion" algorithm, that really doesn't require much math skill as just a basic understanding of algorithm design.
  • (cs) in reply to Mr^B
    Mr^B:
    snip

    I'm still counting the WTFs on that code. Apart from the Alpine nesting (code smell), why multiply the iterator by 20? Just start the iterator at 20 and add 20 each time, no need for that confusing $num variable in there at all. What if the answer is greater than 99999999999? What if the business change their minds and want not divisible by 1..50 or 1..100?

    TRWTF is that apparently some people out there think that it isn't.

    :)

    Thanks. Should have spotted the step 20. Though I would submit that reducing the solution set ahead of time is fair game. With a small enough solution set, the loop is almost irrelevant. (not fair. Quoting only part of your post. But wanted to thank you for the step - I missed that in my search for a solution).

  • mylesb (unregistered) in reply to jDeepBeep

    YOU WIN!

  • (cs) in reply to rumpelstiltskin
    rumpelstiltskin:
    If the interviewee did not realize the problem was about prime numbers, then he is most definitely worth less than someone who did.
    Because all maths grads make excellent commercial programmers? Because people who didn't study maths past the age of 16 can't program for toffee? Or because you do understand the problem, so everyone who doesn't must be significantly inferior to you?
  • mylesb (unregistered) in reply to jDeepBeep
    jDeepBeep:
    I give the coder points for artistic value. Why, if you squint a little, it looks like a formation of geese flying south.

    YOU WIN!

  • An Actual Software Engineer (unregistered)

    The Real WTF is that you guys think this is a solution he would use in a real program. A programming question in an interview is to see if you come up with a solution to a problem (engineering). The solution doesn't have to be the most optimal. It just has to work! Also remember in an interview the only resource you have is your brain, and his solution works so he passed. Only a retarded Noob would think otherwise.

  • Keith (unregistered) in reply to anoncow
    anoncow:
    jDeepBeep:
    I give the coder points for artistic value. Why, if you squint a little, it looks like a formation of geese flying south.

    East.

    Actually, the right side of MY screen points southwest.

  • (cs) in reply to More
    More:
    JimM:
    More:
    No offense. But anybody who writes 14 nested if statements, and don't think: "Surely there must be a better way to do this." is not someone I want to work with.
    Where's your evidence that he didn't think "Surely there must be a better way to do this."? He may well have been thinking that, but didn't know the "better way" off the top of his head and therefore went with the solution that he did know (rather than doing nothing at all).
    Well, anybody who can't think of a better solution is not somebody I'd want to work with either. Just imagine having to maintain that person's code *shudders*
    Then I'm pleased that say that I will never have the pleasure of working with you...
  • (cs) in reply to Ebs2002
    Ebs2002:
    From the original sidebar (that people haven't been reading, it seems)
    Well, in our discussion afterwards I asked him if he could think of any shorter or more efficient ways to write the code. He responded that maybe he would have considered writing a 'while' block to generate the if statements.
    So, yes, the interviewer DID prod him for a more efficient answer.
    The tasks are mostly to check their mathematical ability rather than their programming chops, as the job involves a LOT of mathematical stuff
    Yes, the job involved a LOT of math, so basic high school math principles should be known.
    His code for calculating the Fibonnaci sequence didn't work either - it printed '2' 40,000,000 times
    One of the first algorithms we're taught in college. It's the definitive "Recursion" algorithm, that really doesn't require much math skill as just a basic understanding of algorithm design.
    Thanks for the update - answers a lot of my questions (and makes you wonder why all that info wasn't posted over here - have we all just been trolled by Jake?!?).

    I'm intrigued by the concept that Fibonacci is regarded as the definitive recursion algorithm though, given that it's actually as efficiently solved using a static loop. Factorial is the definitive recursion algorithm, surely...

  • IA (unregistered)
        public static void main(String[] args) {
    		long start = System.currentTimeMillis();
    		int cnt = 20;
    		
    		int[] nums = new int[cnt];
    		for (int i = 0; i < cnt; i++)
    			nums[i] = i;
    		
    		long min = 1;
    		for (int i = 1; i < cnt; i++) {
    			int num = nums[i];
    			if ( num == 1 )
    				continue;
    			// "subtract" the multiplier from following numbers
    			for (int j = i + 1; j < cnt; j++) {
    				if ( nums[j] % num == 0)
    					nums[j] /= num;
    			}
    			min *= num;
    		}
    		System.out.println(min);
    		System.out.println(System.currentTimeMillis() - start);
        }
    

    No LCM or GCD and runs under 1 ms. :-)

  • RiF (unregistered) in reply to m0ffx
    m0ffx:
    TRWTF is asking for 'ten years experience' in a language that's only been around for thirteen years and has changed a lot.

    Sadly, the reason for this has been mentioned - HR write the ads, and HR don't know about what the company does. It's like the '5 years experience in windows 95' ad posted in 1998.

    The OP is saying that the candidate claimed to have "10 years of PHP" experience.

  • Some bad employee (unregistered) in reply to shinobu

    Hah. I've actually been teaching myself Haskell by going through Project Euler while at work. As a PHP developer.

  • (cs) in reply to Mr^B
    Mr^B:
    No, sorry, the problem is simple enough to not be a distraction from the test *SNIP*

    Simple according to who? You only think it's simple because you ALREADY KNOW how to solve it. Of course the solution is simple; finding the solution is the hard part. And without adequate domain knowledge, a person can't be expected to know how to solve the problem without a reference.

    So unless the interview was for a position that required knowledge and experience solving math problems, then it WAS a distraction.

    Mr^B:
    No, people don't use prime numbers every day, nor the mod function, but I don't think it's unreasonable for *SNIP*

    A "basic grasp" of mathematics is fairly ambiguous. A ten year old has a basic grasp of arithmetic, but does that mean he/she should be able to solve this problem? What's the magic math skill level needed to develop software? And who determines what that is?

    Mr^B:
    When I interview people, I expect them to be in EXACTLY the right mind-set, they're under pressure to deliver, but have to deliver something of acceptable quality.

    Creativity can't be called on demand. If your developers are under pressure to perform, then they're not producing their very best work. Similarly, if you want to fully realize a candidate's skills and the benefit they can provide your company, then you'll make them comfortable during the interview.

    As interviewer you have to ask yourself one question: am I interested in learning what the candidate can offer my company OR can I stuff this warm body into the open position?

    If the interviewer in the article chose the former answer, then I would argue that he failed to capture what he was looking for in the candidate.

  • jcs (unregistered)

    The real WTF is that they expected him to write a PROGRAM to compute the solution!

    It took me less than 2 minutes with a 4-function calculator to figure out that the solution is 232792560...

    A candidate that understands the solution would be left without any code to write, other than multiplying a few constants if they don't have a 4-function calculator available.

    A candidate that doesn't understand the solution wouldn't be able to write a good algorithm for this problem anyway.

    Seriously folks...think these things through before putting them on an interview...

  • epv (unregistered) in reply to Anonymous

    Same basic solution...

    $range = shift;
    
    @numbers = 2..$range;
    
    foreach $current (@numbers) {
    	if($current){
    		for($prime=$current;$prime<=$range;$prime+=$current){
    			if($prime==$current){
    				push @primes, $prime;
    			}else{
    				$numbers[$prime - 2] = 0;
    			}
    		}
    	}
    }
    
    $sum=1;
    foreach $current (@primes){
    	$signature=1;
    	while($current**($signature+1)<$range)
    	{
    		$signature++;
    	}
    	$sum*=$current**$signature;
    }
    
    print $sum;
    
  • (cs)

    Just read the original sidebar - and comments. Pleased to see that it devolved into just as much of a flamewar over there as it did over here ;^)

  • (cs)

    I love math, but I haven't seen math like this in years. In ["community"/"technical"] college, we just had basic math that was mostly computer oriented (binary and hexadecimal numbering systems, etc.), and I don't think there was anything like this in grade 12 calculus so perhaps grade 11... Which was like 5 years ago. I would have had to ask the interviewer what "evenly divisible" meant and hopefully could have come up with a solution like the following (which is really just a dynamic adaption of the original solution):

    #include <stdio.h>
    int smallest_evenly_divisible(int start, int end)
    {
        bool evenly_divisible = false;
        int working_number;
        for(int i=1; !evenly_divisible; i++)
        {
            working_number = i * end;
            evenly_divisible = true;
            for(int j=start; j<end && evenly_divisible; j++)
                evenly_divisible = ((evenly_divisible) && (working_number%j == 0));
        }
        <span style="color:blue;">return(working_number);
    }
    
    int main(int argc, char *argv[])
    {
        printf("%d\n", smallest_evenly_divisible(1, 20));
        return(0);
    }

    Tested with ranges 1 to 10 and 1 to 20. Compiled using MinGW and tested on Vista. Not guaranteed to work. :P I couldn't even think of an acceptably short/descriptive function name at first... I think I originally picked smallest_number_evenly_divisible_by_range. :P So I agree that either this question shouldn't be asked unless this kind of math is required at the job OR the interviewer should be willing to answer any questions the interviewee has about the question. Which is something a lot of people don't seem to realize about interviews... It's OK to ask about stuff like this (unless you're expected to know it for a job that requires it). Especially when the real purpose of the question is to see how you convert the solution to code (or possibly how you go about solving a problem)... You should at least be able to ask the right questions to find out how to solve problems.

  • Mr^B (unregistered) in reply to rcarz
    rcarz:
    Mr^B:
    No, sorry, the problem is simple enough to not be a distraction from the test *SNIP*

    Simple according to who? You only think it's simple because you ALREADY KNOW how to solve it. Of course the solution is simple; finding the solution is the hard part. And without adequate domain knowledge, a person can't be expected to know how to solve the problem without a reference.

    So unless the interview was for a position that required knowledge and experience solving math problems, then it WAS a distraction.

    Mr^B:
    No, people don't use prime numbers every day, nor the mod function, but I don't think it's unreasonable for *SNIP*

    A "basic grasp" of mathematics is fairly ambiguous. A ten year old has a basic grasp of arithmetic, but does that mean he/she should be able to solve this problem? What's the magic math skill level needed to develop software? And who determines what that is?

    Mr^B:
    When I interview people, I expect them to be in EXACTLY the right mind-set, they're under pressure to deliver, but have to deliver something of acceptable quality.

    Creativity can't be called on demand. If your developers are under pressure to perform, then they're not producing their very best work. Similarly, if you want to fully realize a candidate's skills and the benefit they can provide your company, then you'll make them comfortable during the interview.

    As interviewer you have to ask yourself one question: am I interested in learning what the candidate can offer my company OR can I stuff this warm body into the open position?

    If the interviewer in the article chose the former answer, then I would argue that he failed to capture what he was looking for in the candidate.

    So you think that dividing a number into another number and seeing if it has a remainder isn't simple? What is simple? 1+1=2?

    I was solving problems like this (for a bit of fun) when I was 8. And that isn't the point, the guy KNEW how to do it he just couldn't translate the mental model he had of the solution into a decent piece of code. That's what a developer does, that's ALL a developer does. He KNEW what he had to do, he just did it in a very bad way.

    This isn't about creativity, it's about knowing how to write good code. Good code is a lot more than just "being functional".

    Look at some of the answers given in the comments, they are all roughly similar, and ALL are more elegant, more maintainable and more flexible than the WTF answer. There's no creativity involved, just an ability to LOOK at some code and think "something's not right here". If you can't spot the unnecessary repetition of the original code then there's really no hope for you and you should stick to Excel and/or Etch-a-sketch.

    I don't want people to be too comfortable in an interview, I have deadlines, people demanding things, a degree of pressure to meet deadlines, etc - I don't have the bandwidth to babysit new developers, I don't have the patience to pair-program with someone who is prepared to submit that for inspection/code-review. So a degree of time pressure in a technical interview is essential.

    As far as what I'm trying to find out, there's only one thing; Can they write good code? I leave the warm body thing to HR, and what they can offer the company to my boss, I want to know if they can code, everything else is a secondary consideration and why there is usually MORE than just a technical interview.

  • Brian W (unregistered) in reply to Mr^B

    You have to know when to go nuts on a complex solution. I see people spending 10 minutes writing a GCD function. Who cares, its a silly interview question. 5 line java program

    public class Haha {
    
        public static void main(String args[])
        {
            Long startTime = System.currentTimeMillis();
            for (int x = 20; x < Integer.MAX_VALUE; x+= 1) {
                if (((x % 11 == 0) & (x % 12 == 0) & (x % 13 == 0) &
                     (x % 14 == 0) & (x % 15 == 0) & (x % 16 == 0) &
                     (x % 17 == 0) & (x % 18 == 0) & (x % 19 == 0) &
                     (x % 20 == 0))) {
    
                        System.out.println("x=" + x);
                        break;
                }
            }
    
            System.out.println("Time:" +( System.currentTimeMillis() - startTime));
        }
    
    }
    

    Ran on my machine in 7.2 seconds. Wrote in 1 minute. Why spend 15 minutes writing a run 1 time program that may save 6 seconds on runtime?

  • Brian W (unregistered) in reply to Brian W

    Opps I used & instead of &&

    Switching to && brought run time down to 1.5 seconds.

    Seriously.. 1.5 seconds to solve a simple problem, works for me.

  • epv (unregistered) in reply to Brian W
    Ran on my machine in 7.2 seconds. Wrote in 1 minute. Why spend 15 minutes writing a run 1 time program that may save 6 seconds on runtime?

    Now solve it for 1 to 700.

  • mauve (unregistered)

    I don't interview people for the position of pocket calculator. I interview people who claim to be programmers. I expect them to demonstrate their best programming.

    Avoiding premature optimisation really entails considering the cost versus a-priori benefit of improving an algorithm. If you consider the problem before writing the brute force algorithm it's a clear win, which is why in an interview with 1-on-1 handholding, I would expect candidates to arrive at the GCD method.

    Put another way, I don't want to have to rewrite my employees' sloppy algorithms just because they couldn't be bothered to think a problem through (or look it up), and the interview is my opportunity to ensure I won't.

  • (cs) in reply to mauve
    mauve:
    I don't interview people for the position of pocket calculator. I interview people who claim to be programmers. I expect them to demonstrate their best programming.

    Avoiding premature optimisation really entails considering the cost versus a-priori benefit of improving an algorithm. If you consider the problem before writing the brute force algorithm it's a clear win, which is why in an interview with 1-on-1 handholding, I would expect candidates to arrive at the GCD method.

    Put another way, I don't want to have to rewrite my employees' sloppy algorithms just because they couldn't be bothered to think a problem through (or look it up), and the interview is my opportunity to ensure I won't.

    Just out of curiosity, if they arrived at the prime solution, would you expect them to create an IsPrime() function on the spot?

  • Brian W (unregistered) in reply to epv

    This is an interview question, not a app I am shipping to a customer.

  • (cs) in reply to mauve
    mauve:
    Avoiding premature optimisation really entails considering the cost versus a-priori benefit of improving an algorithm. If you consider the problem before writing the brute force algorithm it's a clear win, which is why in an interview with 1-on-1 handholding, I would expect candidates to arrive at the GCD method.
    It's kind of a moot point, because the OPer clarified in the forum that the point of setting this was to test the candidates maths knowledge, BUT if this was purely a programming test would you still think this was a suitable question, and would you still expect the GCD method? What if the candidate didn't know it? It's not something I've ever learned explicitly (although I expect the principles behind it were covered at some point when I was at school), and as I said previously I've not studied maths for 16 years so it's hardly surprising that something with no day-to-day relevance is going to go by the wayside...
  • (cs) in reply to Mr^B
    Mr^B:
    So you think that dividing a number into another number and seeing if it has a remainder isn't simple? What is simple? 1+1=2?

    I was solving problems like this (for a bit of fun) when I was 8.

    I'm not surprised by that. You project your own skills and interests on others, and then wonder why they fall short of your expectations. It's great that you love math, but not everyone does. And thinking that every decent developer should have a basic understanding of "simple" math is unrealistic.

    Mr^B:
    And that isn't the point, the guy KNEW how to do it he just couldn't translate the mental model he had of the solution into a decent piece of code. That's what a developer does, that's ALL a developer does. He KNEW what he had to do, he just did it in a very bad way.

    You're right. Several solutions posted in the comments show that it wasn't the most elegant solution. I'm not defending the code so much as pointing out the absurdity of the question.

    Mr^B:
    This isn't about creativity, it's about knowing how to write good code. Good code is a lot more than just "being functional". *SNIP*

    Software developers don't "write code", they solve problems using computers. It's really easy to judge someone for not being able to solve a "simple" math problem because the solution is already defined. As software developers, it is our job to solve problems that don't necessarily have solutions yet. And THAT requires creativity.

    You're reminding me of the old saying "penny-wise, dollar-foolish". You look at it as babysitting new developers when you should be thinking of the return on your investment. I'm not suggesting that you hire any idiot that applies. But don't be surprised if you can't find a unicorn in your sock drawer using a metal detector.

    TRWTF is that you want a code monkey and not a software developer.

  • Bobo (unregistered) in reply to Brian W
    Brian W:
    Ran on my machine in 7.2 seconds. Wrote in 1 minute. Why spend 15 minutes writing a run 1 time program that may save 6 seconds on runtime?

    Thank you, you have just simply made the point for all of us who understand why this can be a useful interview question.

  • Mr^B (unregistered) in reply to rcarz
    rcarz:
    I'm not surprised by that. You project your own skills and interests on others, and then wonder why they fall short of your expectations. It's great that you love math, but not everyone does. And thinking that every decent developer should have a basic understanding of "simple" math is unrealistic.

    I don't project, I was just stating that if it's possible for an under 10 to grasp the concept it shouldn't be beyond the wit of a 25+ year old programmer. My point HAS already been proved because the original code uses % which means that he has grasped the concept, he just didn't implement it in a very good way. And the implementation is what we are after, not the maths.

    And, no, it's not unrealistic at all. I've been hiring and firing developers for over 10 years and each and every one I have hired has been able to understand the concept of division.

    rcarz:
    You're right. Several solutions posted in the comments show that it wasn't the most elegant solution. I'm not defending the code so much as pointing out the absurdity of the question.

    Software developers don't "write code", they solve problems using computers. It's really easy to judge someone for not being able to solve a "simple" math problem because the solution is already defined. As software developers, it is our job to solve problems that don't necessarily have solutions yet. And THAT requires creativity.

    You're reminding me of the old saying "penny-wise, dollar-foolish". You look at it as babysitting new developers when you should be thinking of the return on your investment. I'm not suggesting that you hire any idiot that applies. But don't be surprised if you can't find a unicorn in your sock drawer using a metal detector.

    TRWTF is that you want a code monkey and not a software developer.

    No, I want both, and I can get both, and I have got both before so I demand both again. Probably why I will look at an average of 100 CVs, interview about 10 people, and hire just one. I want a lot (and pay a lot) so I demand a lot. I also want people that I can learn from, who share my enthusiasm for solving problems, talking about design patterns, arguing/discussing best solutions, etc... I don't want a "yes" man, neither do I want a plank.

    I want creativity too, but within the bounds of good coding and design practice.

    If you're happy to hire a developer/coder who churns out rubbish like that then go ahead, fewer CVs for me to reject and interviews to terminate early...

    I think it's "penny wise, pound foolish", "cent wise, dollar foolish" just sounds wrong.

    :)

  • Glazius (unregistered)

    Sure, it's a suitable programming test.

    def map_reduce_smallest_div(number):
    
        retval = 1
        while reduce(lambda x, y: x + y,
                     map(lambda x: retval % x, range(1, number+1))):
            retval += 1
    
        return retval
    

    Of course it's O(huge), but it works.

  • ThingGuy McGuyThing (unregistered) in reply to Mr^B
    Mr^B:
    ThingGuy McGuyThing:
    If the interviewer had wanted a generic LCM algorithm, he should have asked for one.

    Because often the people asking the questions in your job won't KNOW what they actually want. That's why we have things like design patterns and that's why we try and write code that is flexible/extensible and all the stuff that developers SHOULD be taught about code. Rather than the "oh, it works, just stick it in" and then it becomes someone else's problem. "Technical Debt" is the term.

    Yes, but in a normal situation, you'd have the context of the problem, and be able to make that call. In this situation, is it a constant you just need to whip up, or is it a function that will be used multiple times with multiple parameters? Without context, it's impossible to know. If it's the former, then the no-thinking-brute-force approach is the appropriate one, in my opinion.

  • Steve (unregistered)

    Come on guys, there are new articles to flame each other about now.

  • Tom JP (unregistered)
    import operator
    
    def range_multiple(n):
      "returns the smallest positive integer that evenly divides each of 1..n"
      
      # record of how many times each prime factor occurs
      prime_factors = {}
    
      # prime factor each value from 2 to n (1 has no prime factors)
      for factor in range(2, n+1):
        divisor = 1
    
        # loop until all divisors have been divided out
        while factor > 1:     
          count = 0
          divisor += 1
    
          # count number of times divisor is in factor
          while factor % divisor == 0:  
            count += 1
            factor /= divisor
          
          # record divisor count if it is greater than previous max
          if divisor not in prime_factors or count > prime_factors[divisor]:
              if count: # if current value is actual divisor
                prime_factors[divisor] = count
    
      # multiply all powers of prime factors together
      return reduce(operator.mul, [p**n for p,n in prime_factors.items()])
      
    print range_multiple(1000)
    

    There you go, punks. The factoring could be made more efficient, but it runs much better than the brute force crap. Runs for n=1000 in under a second. (result has 433 digits btw)

    You're welcome.

  • More (unregistered) in reply to rcarz
    rcarz:
    Software developers don't "write code", they solve problems using computers. It's really easy to judge someone for not being able to solve a "simple" math problem because the solution is already defined. As software developers, it is our job to solve problems that don't necessarily have solutions yet. And THAT requires creativity.

    You're reminding me of the old saying "penny-wise, dollar-foolish". You look at it as babysitting new developers when you should be thinking of the return on your investment. I'm not suggesting that you hire any idiot that applies. But don't be surprised if you can't find a unicorn in your sock drawer using a metal detector.

    TRWTF is that you want a code monkey and not a software developer.

    Code monkey? This example is an extremely badly written piece of code that does exactly what the customer (interviewer) asked for. That is what a code monkey does.

    A software developer can decipher requirements (“hey, this is a maths based firm… maybe they would like it to work for numbers other than 20”), sk questions about things that are still unclear (“Is this a once off program? If it is, don’t you think it would be better to just use a calculator”), and then write an easily maintainable, readable, program that doesn’t take forever to execute.

  • Tom JP (unregistered) in reply to Glazius
    Glazius:
    Sure, it's a suitable programming test.
    def map_reduce_smallest_div(number):
    
        retval = 1
        while reduce(lambda x, y: x + y,
                     map(lambda x: retval % x, range(1, number+1))):
            retval += 1
    
        return retval
    

    Of course it's O(huge), but it works.

    Wanna get horrible? Cut out the fat.

    def map_reduce_smallest_div(number):
        retval=1
        while any(retval%-~x for x in range(number)):retval+=1
        return retval
    
  • Stephen (unregistered) in reply to K&T

    True,

    But as many, many people have pointed out. You're not testing coding ability here. Your testing mathematical ability. And interviews are artifically stressful environments. So dont be upset if the the guy produces the dumbest thing that works... worry if he produces and overcomplex thing that doesnt work.

    I really really wish more employers (mine included) would do some research on interview situations. I've seen the wrong people hired and the wrong people sent home often because the interviewer doesnt understand how to interview someone to find out what they know.

    An interview can be as frightening to a interviewee as dangling them off a cliff, upside down and setting fire to the rope. Would you seriously expect to hand someone in that situation a pen and paper and say.. Now solve this prime number test for smart people we found off the web. Oh and by the way if you dont we're not gonna blow the fire out.

    Stephen

  • Thunder (unregistered) in reply to sudo make me a sandwich
    sudo make me a sandwich:

    Either way, I'd still take a guy who would use a brute-force 2 nested loop approach over a guy who would decide it's better go wild with copy-paste.

    To brute force it, you only need one loop:

            int x = 20;
            for (int y = 2; y < 20; y++) {
                if ((x%y) == 0) {
                    continue;
                } else {
                    x+=20;
                    y = 2;
                }
            }
    
    
  • Dave (unregistered) in reply to Addison
    Addison:
    Dave:
    Addison:
    DaStoned:
    It's a puzzle. Programmers don't solve puzzles for work.

    I'd solve it similarly. I don't give a crap about puzzles and solving them. The computer does all the work, gives me the answer and we can all continue with more pressing matters. Brute-force is faster than coding a more intelligent algorithm.

    Why hello TopCod3r.

    Jokes aside, let's say you were making a web application (it was a PHP interview after all). You use brute force instead of taking 2 minutes to come up with something better (it's not a hard question). What happens to your server when 10,000-100,000 requests come through at once?

    Last time I checked reducing processing requirements by 1000 fold was a good thing.

    But it doesnt matter cos the result would be in the cache by then. Either that or I'd move it into a stored procedure on the db.

    Fair enough. Only now run your stored procedure 100,000 times and tell me what happens. Nothing good, considering 25202111317*19 will do the same thing.

    Then you call the db admin and complain about why the db is so slow.

  • SeanJA (unregistered) in reply to IA

    continue? that is sort of like using goto:

    Why not just use if ( num != 1 ) instead? it does the check each loop anyway...

  • Pentium100 (unregistered)

    Just a quick question:

    If someone told you to somehow dig a 1m wide and 0.5m deep hole, would you hire this machine to do the digging because the requirement might change to a 1km wide and 500m deep? Or just a man with a shovel?

  • Strilanc (unregistered)

    The post gives the really naive solution, but applying lcm iteratively is still sortof naive. You can get a better asymptotic complexity, and a simpler algorithm, by generating then using a list of primes up to 20.

    max = 20
    #don't actually use fixed primes like this
    #use a fast sieve to generate them
    primes_up_to_max = [2,3,5,7,11,13,17,19]
    n = 1
    for p in primes_up_to_max:
    	i = p
    	while (i <= max):
    		i *= p
    		n *= p
    print n
  • Mogri (unregistered) in reply to mcwyrm
    mcwyrm:
    Wow.

    max = 20 ans = 1

    for i = max to 1{ if mod(ans, i) != 0 then ans *= i }

    return ans

    Faster to type than your nested loops, and really - the obvious way to do it, no?

    Obviously wrong. It'll end up with too many factors of 2. If your loop ran 2 to max, then it'd work.

  • tbrown (unregistered) in reply to Bobo
    Bobo:
    Maybe it's just me, but when I ask (or when I'm asked) a programming question on an interview, I expect the answer to be both elegant and efficient.

    It's fine to start out with "well, the naive way would be to loop over all numbers and see which one is divisible by 1-20", etc.

    But if anyone thought an answer like this is the "right" one, I definitely do not want to be working with them.

    It's amazing that so many people miss the point of these "puzzle" questions. It's not to get the right answer - it's to show how you think and how you go about solving a problem. The fact that something like this would rarely be required on the job is irrelevant.

    Ding ding ding!! Yes!!

    For example, I can't tell you how much I dislike candidates whose first response, for almost any question, is "I would do a google search, look through MSDN KnowledgeBase, etc. and see what other people have done to solve this problem, evaluate their solutions, yadda yadda yadda..." If someone has to resort to a literature search for every frickin' coding problem that rises up and smacks 'em in the face then they're not going to be the most productive of developers, are they?

    But most of all, that type of answer makes it completely impossible to judge how good a developer a candidate really is (or might be). I guess I need to be armed with a laptop and turn it over to the candidate and say, "go for it, you have 30 minutes to give me a working solution in C# code!"

    (captcha: validus -- how apropos)

  • NonEulerian (unregistered)

    A brute force solution may well be best if the problem size can be bounded, and is more likely to work correctly in an off-the-cuff answer.

    bool IsDiv( const int n ) {
       for ( int i=1; i<=10; i++ ) {
          if ( n % i != 0 ) return false;
       }
       return true;
    }
    
    ...
    while ( ! IsDiv( ++n ) ) {}
    ...
    

    That said, I like math tricks too.

  • (cs) in reply to Pentium100
    Pentium100:
    Just a quick question:

    If someone told you to somehow dig a 1m wide and 0.5m deep hole, would you hire this machine to do the digging because the requirement might change to a 1km wide and 500m deep? Or just a man with a shovel?

    Awesome. It's like 9 women for 1 baby in 1 month. I salute you, sir.

  • xian (unregistered)

    Personally i think this is a great question. Who cares if they guy can write PHP, Java, C or any other language, typing out the code should be by far the simplest part of any project. I can get some kid straight out of high school to take a mathematical function and reproduce it in code (i bet i could train a monkey with enough time) I wanna know if my candidates can think about problems in an intelligent manor, breaking them down into pieces then reassembling them into a solution. If they can, chances are i can tell them to deliver it in any of a dozen languages even if they don't know them and they'll go figure out the syntax. Or, more importantly, they'll be able to determine the proper tool (language) for the job and really deliver a proper solution.

    These are exactly the types of questions you ask when what you want is a conscious being as an employee, not a code monkey.

    -x

  • Bobble (unregistered) in reply to Ren

    Nine women for one baby in one month is doable and has a simple implementation.

    Send each woman out to a public park with orders to kidnap a baby. Worst case, all nine get caught, but I'll still have 7 more months to bring the project in on time. Best case, I end up with nine babies in that month and can pick the best possible one to satisfy my client's needs.

Leave a comment on “Out of All the Possible Answers...”

Log In or post as a guest

Replying to comment #221751:

« Return to Article