数丑陋 代码(C)
本文地址: http://blog.csdn.net/caroline_wendy
题目: 我们把仅仅包括因子2, 3 和 5的数称作丑数. 求按从小到大的顺序的第5个丑数.
能够设置一个数组包括所须要的丑数, 依次比較乘以2, 乘以3, 乘以5的最小的数, 最后返回结果.
如第5个丑数是5, 如1, 2, 3, 4(2*2), 5均是丑数.
代码:
/*
* main.cpp
*
* Created on: 2014.6.12
* Author: Spike
*/ /*eclipse cdt, gcc 4.8.1*/ #include <stdio.h>
#include <stdlib.h>
#include <string.h> int Min(int number1, int number2, int number3) {
int min = (number1 < number2) ? number1 : number2;
min = (min < number3) ? min : number3; return min;
} int GetUglyNumber(int index) {
if (index <= 0)
return 0;
int* pUglyNumbers = new int[index];
pUglyNumbers[0] = 1;
int nextUglyIndex = 1; int* pMultiply2 = pUglyNumbers;
int* pMultiply3 = pUglyNumbers;
int* pMultiply5 = pUglyNumbers; while (nextUglyIndex < index) {
int min = Min(*pMultiply2*2, *pMultiply3*3, *pMultiply5*5);
pUglyNumbers[nextUglyIndex] = min;
while (*pMultiply2*2 <= pUglyNumbers[nextUglyIndex])
++pMultiply2;
while (*pMultiply3*3 <= pUglyNumbers[nextUglyIndex])
++pMultiply3;
while (*pMultiply5*5 <= pUglyNumbers[nextUglyIndex])
++pMultiply5; ++nextUglyIndex;
}
int ugly = pUglyNumbers[nextUglyIndex-1];
delete[] pUglyNumbers;
return ugly; }
int main(void)
{
int num = 5;
int result = GetUglyNumber(num);
printf("result = %d\n", result); return 0;
}
输出:
result = 5
版权声明:本文博主原创文章,博客,未经同意不得转载。