Google Interview Question for Software Engineer / Developers


Country: United States
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
17
of 19 vote

These are basically referred to as ugly numbers . Here is the code for it:
a. Take variables for multiples of 2,3,5,7.
b. Everytime find a minimum of the multiple.
c. Store 1 in the first index as it is multiple of all.
d. Find the minimum of all the multiples of 2,3,5,7. Whenever that minimum is equal to any of the multiples. Store that multiple in the indexes assigned for 2,3,5,7 and also multiply that element with the number to get the next higher multiple in next iteration.

#include <stdio.h>
#include <conio.h>
#include <malloc.h>
int min(int a,int b)
{
	return (a<b?a:b);
}
int min(int a,int b,int c,int d)
{
	return min(a,min(b,min(c,d)));
}
void printAllMultiples(int n)
{
	unsigned *ugly=(unsigned *)malloc(sizeof(ugly));
	unsigned next_multiple_2=2;
	unsigned next_multiple_3=3;
	unsigned next_multiple_5=5;
	unsigned next_multiple_7=7;
	unsigned i2=0,i3=0,i5=0,i7=0;
	ugly[0]=1;
	unsigned next_ugly_no;
	int i;
	printf(" %d ",ugly[0]);
	for(i=1;i<n;i++)
	{
		next_ugly_no=min(next_multiple_2,next_multiple_3,next_multiple_5,
						 next_multiple_7);
		*(ugly+i)=next_ugly_no;
		printf(" %d ",next_ugly_no);

		if(next_ugly_no==next_multiple_2)
		{
			i2=i2+1;
			next_multiple_2=ugly[i2]*2;
		}
		if(next_ugly_no==next_multiple_3)
		{
			i3=i3+1;
			next_multiple_3=ugly[i3]*3;
		}
		if(next_ugly_no==next_multiple_5)
		{
			i5=i5+1;
			next_multiple_5=ugly[i5]*5;
		}
		if(next_ugly_no==next_multiple_7)
		{
			i7=i7+1;
			next_multiple_7=ugly[i7]*7;
		}
	}
	
} 
int main()

{
	printAllMultiples(20);
}

- vgeek July 29, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

very good solution!! +1

- algos July 30, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

@vgeek

I doubt the correctness of your algorithm. Could you please clarify if your procedure takes care of producing numbers that are multiples of a subset of powers of 2,3,5 & 7. For ex: will you algorithm be able to generate 2^2 * 3^2 * 5^2 * 7^2?

- Murali Mohan July 30, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

yes, this algo generating below cases

2^2 * 3^2 * 5^2 * 7^2 -> 44100
2^1 * 3^2 * 5^2 * 7^2 -> 22050

- algos July 30, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is an ugly number problem, and vgeek's solution is better. Miguel Oliveira 's solution is very easy to understand, but waste of space for the numbers which are currently not used, and increased the corresponding time on PUSH operation.

- pk0119 July 31, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

this is sooo clever!

- galli August 06, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

1) it is very hard to argue about the correctness of this, because e.g.
the number 11 will be missing ;)

- megmondoEmber August 18, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

my mistake :) forget it

- megmondoEmber August 18, 2013 | Flag
Comment hidden because of low score. Click to expand.
16
of 20 vote

The key here is to use a heap (aka priority queue). Start with number 1 and add it to the heap. Then, do a loop
a) Pop the minimum value from the heap
b) Print this minimum
c) Add minimum*2, *3, *5 and *7 to the heap

If we want N numbers, the complexity will be O(N log N).
Note that since i,j,k,l >=0, the first number should be 1, not 2.

- Miguel Oliveira July 29, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Simply rocks! :)

- Murali Mohan July 29, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

+1

- algos July 29, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 2 votes

how to deal with when duplicate values arrives.. like 2*5,5*2,4*3,3*4.....?? also the series should be 2,3,4,5.....(4 is missing)

- Prateek July 29, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

To deal with duplicates, you can use a hash table.
About the missing 4, it should be a mistake. 4 must be in the sequence (note that 8 is there)

- Miguel Oliveira July 29, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Does this solution have a space complexity of 4^N?

- houseUrMusic July 29, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Why 4^N? It's O(N), this is a sample implementation for small values. Note that we ignore repeated values and we could also ignore values to the heap when we already have N values in the heap.

#include <queue>
#include <vector>
#include <iostream>
using namespace std;
int primes[] = {2, 3, 5, 7};
char seen[1000000]; // for large values, use a hash table instead

int main() {
    int N, i, j, next, minimum;
    cin >> N;
    priority_queue<int, vector<int>, greater<int> > heap;
    heap.push(1);
    for (i = 0; i < N; i++) {
        minimum = heap.top();
        heap.pop();
        cout << minimum << endl;
        for (j = 0; j < 4; j++) {
            next = minimum * primes[j]; // careful with overflow
            if (!seen[next]) {          // for large values
                seen[next] = 1;
                heap.push(next);
            }
        }
    }
    return 0;
}

- Miguel Oliveira July 29, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Yah Sorry wasn't thinking, its 4*N space. Awesome solution :)

- houseUrMusic July 29, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Although this solution is easier to understand, vgeek's solution is O(N), thus better than this one.

- Miguel Oliveira July 29, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This can be done in O(n). Will post my algo, when I will be free.

- Nitin Gupta July 30, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Miguel: Using this solution we will never get 22, 44 etc.
But these numbers can be obtained from equation putting i = 11 and rest 0

- Asya July 30, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

if i=11 then 2^11 = 2048 not 22

- algos July 30, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This does not seem to be correct, according to this algorithm, the output will be:
1, 2, 3, 5, 7, 4, 6 10, 14, 9, 15 21...
instead of:
1, 2, 3, 4, 5, 6, 7, 8....

- Anonymous July 30, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

it's a heap (priority queue), not a queue. The heap will get the minimum value, not the FIFO order

- Miguel Oliveira July 30, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

As we need to remove duplicates, a BST could serve better than heap: no need for the additional hash table. And still O(N log N). On the other hand, BST uses pointers and can't be stored in an array like a heap.

Also, we can't stop when we have N items in the tree - e.g. say N=4, the tree would contain 2, 3, 5, 7 after the first round. We must keep adding until we output all N items.

- galli August 10, 2013 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

this sol. applies for 2^x * 3^x * 5^x * 7^x

so your ans. set should be incomplete

- beyondfalcon August 14, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

(y)

- Anon November 26, 2013 | Flag
Comment hidden because of low score. Click to expand.
2
of 2 votes

explicitly avoid duplicate (according to the CTCI book)

*** 2, 3, 5, 7 factor sequence ****
from collections import deque

def min4(a, b, c, d):
	l = [a, b, c, d]
	return min(enumerate(l), key = lambda x: x[1])

# return first N numbers whose only prime factors are 2,3,5,7
def gen_2357_seq(N):

	q2 = deque([2])
	q3 = deque([3])
	q5 = deque([5])
	q7 = deque([7])

	res = [1]
	for i in range(1, N):
		idx, m = min4(q2[0], q3[0], q5[0], q7[0])
		
		res.append(m)
		
		q7.append(7 * m)
		if idx == 3:
			q7.popleft()
			continue
		q5.append(5 * m)
		if idx == 2:
			q5.popleft()
			continue
		q3.append(3 * m)
		if idx == 1:
			q3.popleft()
			continue
		q2.append(2 * m)
		q2.popleft()
	return res

- raingo December 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Miguel Oliveira's is not optimized. it should be done in O(N)
vgeek's is O(N)

- luciany July 27, 2014 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

limit=10
print "looping for", limit ,"times"

numlist = ["0000"]
#-----------------------------------------
def generator(nlist,count):
    for i in range(1,count):
        nlist.append(str(i)+str(i-1)+str(i-1)+str(i-1))
        nlist.append(str(i-1)+str(i)+str(i-1)+str(i-1))
        nlist.append(str(i-1)+str(i-1)+str(i)+str(i-1))
        nlist.append(str(i)+str(i)+str(i-1)+str(i-1))
        nlist.append(str(i-1)+str(i-1)+str(i-1)+str(i))
        nlist.append(str(i-1)+str(i)+str(i)+str(i-1))
        nlist.append(str(i)+str(i)+str(i)+str(i-1))
        nlist.append(str(i-1)+str(i-1)+str(i)+str(i))
        nlist.append(str(i-1)+str(i)+str(i)+str(i))
        nlist.append(str(i)+str(i)+str(i)+str(i))
    #print numlist
    #print count

#-----------------------------------------
    
generator(numlist,limit)
#print numlist

for item in numlist:
    part = list(item)
    #print part
    calcOP = (2**int(part[0]))*(3**int(part[1]))*(5**int(part[2]))*(7**int(part[3]))
    print calcOP

This should do it in python.

- sandeep July 30, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I ran that in Python and it did not generate 8 (i,j,k,l){3,0,0,0} or 12 (i,j,k,l){2,1,0,0} which should be part of the list of numbers generated.

- schroeder.carl.j July 30, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

below numbers can't be generated using this formula

1. all PRIME numbers that are greater than 7
2: all numbers that are divisible by PRIME numbers greater than 7

numbers excluding from above two cases can be generated

- algos July 30, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

so in this question
2^i * 3^j * 5^k * 7^l

should mean 2 to the power of i multiplied by 3 to the power of j and so on..
thus
for i=1,j=1,k=1,l=1
shouldnt the first number be
2*3*5*7 = 210 ?

- annonymous July 30, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

exponents >= 0, not >= 1

- Miguel Oliveira July 30, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

so even if exponents are 0, the first number would be 1 followed by 210 !! The sequence 2,3,5,6,7,8,9. seems incorrect to me !!

- annonymous July 30, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

those 4 letters i,j,k and l mean that the exponents don't need to have the same value
2 = 2^1 * 3^0 * 5^0 * 7^0
3 = 2^0 * 3^1 * 5^0 * 7^0
4 = 2^2 * 3^0 * 5^0 * 7^0
etc
Rohit made some mistakes, 1 and 4 are missing from the sequence

- Miguel Oliveira July 30, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Thanks that was very helpful

- annonymous July 30, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

For the heap solution, please use java's BigInteger since numbers will get bigger for higher exponents.

- amitb2108 July 30, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

this should print out all the nos. whose only prime factors are 2,3,5 or 7. We will print out 1 by default. We should try to reduce a number to 1 by dividing it with different powers of 2,3,5 and 7. if the number reduces to 1 then print it out.

std::cout << 1 << " ";
size_t n = 2;

void reduce( size_t& num, size_t divisor )
{
while( num % divisor == 0 )
num /= divisor;
}

int main()
{
std::cout << 1 << std::endl;
size_t num = 2;
while( true )
{
num = reduce( num, 2 );
num = reduce( num, 3 );
num = reduce( num, 5 );
num = reduce( num, 7 );
if( num == 1 )
std::cout << num << std::endl;
num++;
}
}

complexity: O(N)

- Raja July 31, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

this is not complexity O(N). It is still O(NlogN). The logN comes from your reduce function.

- houseUrMusic August 07, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

For anybody that is interested, this question is very, very similar (and requires a nearly identical solution) to question 7.7 in Cracking the Coding Interview 5th ed.

"Design an algorithm to find the kth number such that the only prime factors are 3, 5, and 7."

- Will August 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here's a dynamic programming approach that I think does it in O(n) with a memory space of ~N.

bool array[N+1];

for(int i = 0; i < N+1; i++)
{
	array[i] = 0;
}

array[1] = true;

int j = 0;
while(j < N+1)
{
	j += 2;
	array[j] = true;
}

j = 0;
while(j < N+1)
{
	j += 3;
	array[j] = true;
}

j = 0;
while(j < N+1)
{
	j += 5;
	array[j] = true;
}

j = 0;
while(j < N+1)
{
	j += 7;
	array[j] = true;
}

for(int i = 0; i < N+1; i++)
{
	if(array[i] == true)
	{
		print i;
	}
}

- David August 07, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

you're mixing 2 different Ns: the n-th number we want and the magnitude (say M) of this number. While the above approaches state the time complexity in terms of "n". Your algorithm is O(M)

- Miguel Oliveira August 07, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Miguel, you are right.

I'm a little hazy on big O notation, but with the constraints of the problem, I think it's still O(n).

To fix this solution, you could let M = 2*N (since 2 is one of the factors, it's not going to use more than 2*N space), then use M for the array length. At the end, you'd have to count how many numbers you had printed and stop when you'd printed the appropriate amount.

Because M is a fixed multiple of N, I believe you can still call it O(N).

- David August 07, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Nevermind, I miscalculated. Using the logic above, it'd be exponential space, M=2^N.

- David August 07, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

N = 1000, answer = 385875
N = 2000, answer = 7077888
N = 3000, answer = 50176000
N = 4000, answer = 228614400

This is clearly an exponential growth..

- Miguel Oliveira August 07, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

My idea is same as Miguel Oliveira's, and the time complexity is O(nlogn), here is my code:

#include <iostream>
#include <vector>
#include <queue>
#include <cmath>

struct quadruple
{
	int i, j, k, l;
	int v;
	quadruple( int i, int j, int k, int l ) : i(i), j(j), k(k), l(l), 
		v( static_cast<int>( pow( 2.0f, i ) *  pow( 3.0f, j ) * pow( 5.0f, k ) * pow( 7.0f, l ) ) ) {}

	bool operator!=( const quadruple& q )
	{
		return v != q.v;
	}
};

struct quadruple_greater
{
	bool operator()( const quadruple& p, const quadruple& q ) const
	{
		return p.v > q.v;
	}
};

void number( int n ) // time complexity O(nlogn)
{
	std::vector<quadruple> result;
	result.reserve(n);

	std::priority_queue< quadruple, std::vector<quadruple>, quadruple_greater > min_heap;
	quadruple q( 0, 0, 0, 0 );
	min_heap.push( q );
	result.push_back(q);

	while( !min_heap.empty() )
	{
		q = min_heap.top();
		min_heap.pop();
		if( result.back() != q ) result.push_back(q);
		if( result.size() == n ) break;
		min_heap.push( quadruple( q.i + 1, q.j, q.k, q.l ) );
		min_heap.push( quadruple( q.i, q.j + 1, q.k, q.l ) );
		min_heap.push( quadruple( q.i, q.j, q.k + 1, q.l ) );
		min_heap.push( quadruple( q.i, q.j, q.k, q.l + 1 ) );
	}

	for( std::vector<quadruple>::iterator it = result.begin(); it != result.end(); ++it )
		std::cout << it->v << "	(" << it->i <<"," << it->j << "," << it->k << "," << it->l << ")" << std::endl;
}

int main( int argc, char* argv[] )
{
	number(9);

	return 0;
}

- weijjcg August 18, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Not going in to time complexity, this is how i wrote the program.

public class PrimeFactors {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		for(int c=2;c<100;c++)
		calculatePrimeFactors(c);
	}
	
	public static void calculatePrimeFactors(int num)
	{
		int i=num;
		while(i>1 && i%7==0)
		{
			i=i/7;
		}
		while(i>1 && i%5==0)
		{
			i=i/5;
		}
		while(i>1 && i%3==0)
		{
			i=i/3;
		}
		while(i>1 && i%2==0)
		{
			i=i/2;
		}
		if(i==1)
		{
			System.out.println(num+"can be broken in to factrs of 2,3,5,7");
		}
		else
		{
			System.out.println(num+" cannot be broken in to factors of 2,3,5,7");
		}
	}

}

- chiranjeevi pavurala August 22, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

its while(i>1 && ....
not sure why it printed ; after i>

- chiranjeevi pavurala August 22, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Any number that conforms to this formula is a number that is divisible by 2 or 3 or 5 or 7. So just loop over the integers and check if any is divisible by 2,3,5 or 7.

public void printNums(int N){
    for(int i = 0; i < N; i++){
        if(isdivisible(i,2) || isdivisible(i,3) || isdivisible(i,5) || isdivisible(i,7))
              System.out.printlnt(i);
    }
}

- karimyehia10@gmail.com August 28, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Solution{

public ArrayList<Integer> sortedOrder(int len){

PriorityQueue<Word> qe = new PriorityQueue<Word>(2*len , Word.com );
ArrayList<Integer> res = new ArrayList<Integer> ();
qe.add(new Word(2,2));
qe.add(new Word(3,3));
qe.add(new Word(5,5));
qe.add(new Word(7,7));
int k = 0;
while( k < len ){
k++;
Word t = qe.poll();
res.add(t.val);
switch( t.calss ){
case 2:
qe.add(new Word(2,2 * t.val));
qe.add(new Word(3,3* t.val));
qe.add(new Word(5,5* t.val));
qe.add(new Word(7,7* t.val));
break;

case 3:
qe.add(new Word(3,3* t.val));
qe.add(new Word(5,5* t.val));
qe.add(new Word(7,7* t.val));
break;
case 5:

qe.add(new Word(5,5* t.val));
qe.add(new Word(7,7* t.val));
break;
case 7:
qe.add(new Word(7,7* t.val));
break;
}
}
return res;
}
}

public class Word{
int class;
int val;
public Word(int cla, int v)
{
class = cla;
val = v;
}

public static Comparator<Word> com = new Comparator<Word>(){
@override
public int compare(Word a , Word b){
if(a.val > b.val ) return 1;
if(a.val < b.val ) return -1;
return 0;
}
}
}

- huihancarl August 31, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

why dont we simply take a loop over numbers and for any no see whether it is divisible by the combination of the given number. if it is then it can be generated else not..

- shubham September 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

that approach is much slower

- Miguel Oliveira September 04, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I took this approach while caching the previous solutions. If the number you're testing is divisible by any of the bases, make that base one and the others 0. Then divide the number by that base, and add the exponents from the quotient (which you have cached). This works in linear time so it should be very fast.

- jboolean December 24, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

think we should use four queues, initialy each queue has only one num 2,3,5,7,we name them q2,q3,q5and q7
then we compare the top of the four queues to get the min, and if min is from q2, then we add *2 to q2, and the *min to q3 q5andq7, if min is from q3, we only add *3 to q3 and the *min to q5 and q7, etc to avoid duplicates

for instance
2 2*2
3 3*2
5 5*2
7 7*2
then 3 is min so
2 2*2
3 3*2 3*3
5 5*2 5*3
7 7*2 7*3
then 4 from q2 is min so
2 2*2 4*2
3 3*2 3*3 3*4
5 5*2 5*3 5*4
7 7*2 7*3 7*4
etc

- Anonymous December 17, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

remeber pop when visit one min

- Anonymous December 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

The solution is very simple:
if a number is divisible by 2, 3, 5 and 7, then that number can be generated by the equation. So, here is the code

for (n=1; n<N; n++)
{
	x = n;
	while (x%2==0) x/=2;
	while (x%3==0) x/=3;
	while(x%5==0) x/=5;
	while(x%7==0) x/=7;
	if (x==1) cout << x << endl;
}

- hossein.khatoonabadi November 10, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I worked on this problem independently and found that my solution is exactly the same as the one from vgeek, however my implementation is shorter and easier to read;

O(N) time O(N) space

void printSequence(int n)
{
	vector<int> v(n);
	v[0] = 1;
	int p2 = 0, p3 = 0, p5 = 0, p7 = 0;
	cout << 1 << endl;
	for (int i = 1; i < n; i++) {
		int n2 = v[p2] * 2;
		int n3 = v[p3] * 3;
		int n5 = v[p5] * 5;
		int n7 = v[p7] * 7;
		int next = min(min(n2,n3),min(n5,n7));
		v[i] = next;
		if (next == n2) p2++;
		if (next == n3) p3++;
		if (next == n5) p5++;
		if (next == n7) p7++;
		cout << next << endl;
	}
}

- 0xF4 December 26, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Question is not clear. Can you please explain the intent with an example or "Miguel Oliveira" can you please help with a pseudo code and a simulation around it please.

- Tackle July 29, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I assume we should print number 1 as well. For large values, we should use a hash table and be careful with overflow in integers multiplication.

#include <queue>
#include <vector>
#include <iostream>
using namespace std;
int primes[] = {2, 3, 5, 7};
char seen[1000000]; // for large values, use a hash table instead

int main() {
    int N, i, j, next, minimum;
    cin >> N;
    priority_queue<int, vector<int>, greater<int> > heap;
    heap.push(1);
    for (i = 0; i < N; i++) {
        minimum = heap.top();
        heap.pop();
        cout << minimum << endl;
        for (j = 0; j < 4; j++) {
            next = minimum * primes[j]; // careful with overflow
            if (!seen[next]) {          // for large values
                seen[next] = 1;
                heap.push(next);
            }
        }
    }
    return 0;
}

- Miguel Oliveira July 29, 2013 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Meh, going to have to heap it after all.
Coffee first, then code :(

vgeeks algorithm is the best I can come up with. Here it is in Python:

def printMultiples(n):
  op = array.array('i')
  i,j,k,l = 0,0,0,0
  mi,mj,mk,ml = 2,3,5,7
  op.append(1)
  print op[0]
  for x in range(1,n):
    op.append(min(mi,mj,mk,ml))
    print op[x]
    if mi == op[x]:
      i = i+1
      mi = op[i]*2
    if mj == op[x]:
      j = j+1
      mj = op[j]*3
    if mk == op[x]:
      k = k+1
      mk = op[k]*5
    if ml == op[x]:
      l = l+1
      ml = op[l]*7

- schroeder.carl.j July 30, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is incorrect. It fails with 22 for example - it is divisible by 2 but we can't get it through 2^i * 3^j * 5^k * 7^l
This question is about factorization strictly by 2, 3, 5 *and* 7.

- Miguel Oliveira July 30, 2013 | Flag
Comment hidden because of low score. Click to expand.


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More