求丑数
大致描述:
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence?
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, ...?
shows the first 10 ugly numbers.
http://poj.org/problem?id=1338
用指針實現:
大致思想:設定三個指針i3,i5,i7.
依次按照每個數字都要乘3,5,7給出下面代碼:
#include <stdio.h>
#include <string.h>
#define MIN(x,y) ((x)<(y)?(x):(y))
int ug[1501];
void init()
{
??? int i;
??? int i2, i3, i5;
??? i2 = i3 = i5 = 1;
??? ug[1] = 1;
??? for (i=2; i<=1500; i++) {
??????? int t = MIN(ug[i2]*2, MIN(ug[i3]*3, ug[i5]*5));
??????? ug[i] = t;
??????? if (t == ug[i2]*2) i2++;
??????? if (t == ug[i3]*3) i3++;
??????? if (t == ug[i5]*5) i5++;
???????
??? }
}
int main()
{
??? init();
??? int n;
??? while (scanf("%d", &n) != EOF) {
??????? if (!n) break;
??????? printf("%d\n", ug[n]);
??? }
??? return 0;
}
?
另外http://hawstein.com/posts/ctci-ch10-math.html?給出了另一種解法,但是該方法不好理解,上述方法更好理解
PS一個筆記:
N個蘋果放到M個盤子中,盤子可以為空是個整數劃分問題
如果盤子不為空可以轉化為盤子為空的問題見鏈接:
http://blog.csdn.net/qq675927952/article/details/6312255
總結
- 上一篇: Cocos沙龙深圳站火热启动 超强阵容
- 下一篇: 简易的灰度处理