Skip to content

Commit 102cdbc

Browse files
committed
Kth multiple of 3,5,7
1 parent b1f87eb commit 102cdbc

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

17-Hard/9-Kth-Multiple.cpp

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
Kth Multiple: Design an algorithm to find the kth number such that the only prime factors are 3, 5,
3+
and 7. Note that 3,5, and 7 do not have to be factors, but it should not have any other prime factors.
4+
For example, the first several multiples would be (in order) 1,3, 5, 7, 9, 15, 21.
5+
*/
6+
7+
#include <iostream>
8+
#include <queue>
9+
10+
using std::cout;
11+
using std::endl;
12+
using std::queue;
13+
14+
int getKthMultiple( int x, int y, int z, int k ) {
15+
queue<int> qX, qY, qZ;
16+
qX.push(1);
17+
qX.push(x);
18+
qY.push(y);
19+
qZ.push(z);
20+
int min;
21+
for( int i=0; i < k; i++ ) {
22+
min = qX.front() < qY.front() ? ( qX.front() < qZ.front() ? qX.front() : qZ.front() ) : (qY.front() < qZ.front() ? qY.front() : qZ.front() );
23+
if( min == qX.front() ) {
24+
qX.pop();
25+
qX.push( min * x );
26+
qY.push( min * y );
27+
qZ.push( min * z );
28+
}
29+
if( min == qY.front() ) {
30+
qY.pop();
31+
qY.push( min * y );
32+
qZ.push( min * z );
33+
}
34+
if( min == qZ.front() ) {
35+
qZ.pop();
36+
qZ.push( min * z );
37+
}
38+
}
39+
return min;
40+
}
41+
42+
int main() {
43+
int k = 10;
44+
int x = 3, y = 5, z = 7;
45+
cout<< getKthMultiple( x, y, z, 10 ) << endl;
46+
}

0 commit comments

Comments
 (0)