Title: We call the numbers that contain only factors 2, 3, and 5 as ugly numbers (Ugly number). For example, 6, 8 are ugly numbers, but 14 is not because it contains factor 7. We used to think of 1 as the first ugly number. Find the 1500th ugly number in order from small to large.
Analysis: This is a wide spread on the network of the face test, it is said that Google has used this problem.
The idea at the beginning of this question is to step through the 1 start, find out the number of 1500 is ugly, and print out.
Implemented as follows:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
BOOL isugly (int d)
{while
(d%2 = 0)
d/=2;
while (d%3 = = 0)
d/=3;
while (d%5 = = 0)
d/=5;
if (d = = 1) return
true;
return false;
}
void Printuglyn (int num)
{
int k = 0;
for (int i= 1; k < num i + +)
{
if (isugly (i))
{
k++;
cout << i << "\ t"
;
}}} int main ()
{
Printuglyn (1500);
return 0;
}
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
There are a lot of calculations, you can use a simple method, the idea is very subtle.
The following number is based on the preceding number *2 or 3 or 5. You can multiply three pointers by 2, multiply by 3, and multiply by 5.
See algorithm implementation:
#include <stdio.h> #include <string.h> #include <iostream> #include <stdlib.h>//#defi Ne min (A, B, C) (((a) > (b))? b):(a)) > (c))? C: ((a) > (b))? (
b):(a)) using namespace Std;
int min (int a, int b, int c) {int t = a > B b:a; Return t> c?
C:t;
} void Finduglyn (int *uglys, int num) {uglys[0] = 1;
int p2 = 0;
int p3 = 0;
int P5 = 0;
int i = 1;
while (I < num) {uglys[i] = min (uglys[p2]*2, uglys[p3]*3, uglys[p5]*5);
if (uglys[i] = = uglys[p2]*2) p2++;
if (uglys[i] = = uglys[p3]*3) p3++;
if (uglys[i] = = uglys[p5]*5) p5++;
i++;
int main () {int num = 1500;
int *uglys = new Int[num];
Finduglyn (Uglys, num); for (int i = 0; i < num; i++) cout << Uglys[i] << "T";
Delete[] Uglys;
return 0; }
Author: csdn Blog hhh3h