《Cracking the Coding Interview》——第7章:数学和概率论——题目7

2014-03-20 02:29

题目:将质因数只有3, 5, 7的正整数从小到大排列,找出其中第K个。

解法:用三个iterator指向3, 5, 7,每次将对应位置的数分别乘以3, 5, 7,取三者中最小的数作为生成的下一个结果。可以一次性生成整个序列,因为这个序列一般不会很长,增长率是指数级的。

代码:

 1 // 7.7 Find the kth number that has no prime factors other than 3, 5 or 7.

 2 #include <algorithm>

 3 #include <cstdio>

 4 #include <vector>

 5 using namespace std;

 6 

 7 int main()

 8 {

 9     vector<int> v;

10     int n = 0;

11     int p3, p5, p7;

12     int res3, res5, res7;

13     int min_res;

14     const int MAX = 1000000000;

15     

16     v.push_back(1);

17     p3 = p5 = p7 = 0;

18     while (true) {

19         res3 = v[p3] * 3;

20         res5 = v[p5] * 5;

21         res7 = v[p7] * 7;

22         min_res = min(res3, min(res5, res7));

23         if (min_res > MAX) {

24             break;

25         }

26         if (res3 == min_res) {

27             ++p3;

28         }

29         if (res5 == min_res) {

30             ++p5;

31         }

32         if (res7 == min_res) {

33             ++p7;

34         }

35         v.push_back(min_res);

36     }

37     printf("count = %u\n", v.size());

38     

39     while (scanf("%d", &n) == 1) {

40         if (n < 0 || n >= (int)v.size()) {

41             printf("Out of range.\n");

42         } else {

43             printf("%d\n", v[n]);

44         }

45     }

46     

47     return 0;

48 }

 

你可能感兴趣的:(interview)