LinkedIn

  www.linkedin.com
  www.linkedin.com

Interview Question

Contract Ruby On Rails Software Engineer Interview Mountain View, CA

Describe a routine which returns the set of integers in

  {1..100} divisible without remainder by 3 but not by 9.
Tags:
algorithm, ruby
Answer

Interview Answer

10 Answers

0

I'm assuming the question wants us to find integers that are divisible by 3 but not by 9. This can be easily obtained using a mod function inside the following if statement: if(number % 3 == 0 && number % 9 != 0)
Here is a short program I wrote in c++ to show how to solve this problem. Instead of returning the set of integer, I just printed them out on the screen:

#include <vector>
#include <iostream>
using namespace std;

int main(int argc, char** argv)
{
   int i = 0;
   vector<int> list;
   vector<int>::iterator it;
   for(i = 1; i <= 100; i++)
   {
        if(i%3 == 0 && i%9 != 0)
        {
           list.push_back(i);
        }
   }
   for(it = list.begin(); it != list.end(); it++)
   {
        cout << *it << endl;
   }
   return 0;
}

If I missed anything, please let me know. Happy coding and problem solving!

Tyler on Feb 11, 2012
0

That'll certainly work, Tyler, but the OP indicated he was interviewing for a Ruby On Rails - not C++ - gig.

Anon on Feb 11, 2012
3

put those integers into an array, pick every third element, out of which discard every third element.

guest on Feb 13, 2012
0

python
[x for x in range(0,100) if x % 3 == 0 and x % 9 != 0]

Tom on Feb 26, 2012
1

1) start from number = 3
Loop while(number <= 100)
2) display number
3) number = number+3, display number
4) number = number+6
Loop

Vicky on Mar 19, 2012
0

(1..100).map { |i| (i % 3).zero? && !(i % 9).zero? ? i : nil }.compact

Chris on Aug 14, 2012
2

(1..100).select { |x| x%3 == 0 && x%9 != 0

Matt on Apr 21, 2013
0

matt has the best answer

ss on Sep 23, 2013
0

A variation on Matt's answer:

(1..100).select { |n| n % 3 == 0 }.reject { |n| n % 9 == 0 }

Sharon on Jul 14, 2014
0

The requirement doesn't say if the input has to be a Range. If it doesn't have to be, then we don't need to traverse each element but to simply calculate it.

def get_nums_by_3_not_by_9(max)
    arr = []
    x = max.to_i / 3

    x.times do |i|
        next if i % 3 == 0
        arr << i * 3
    end

    return arr
end

cel on Nov 15, 2014

Add Answers or Comments

To comment on this Question, Sign In with Facebook or Sign Up