本文地址: 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
编程算法 - 丑数 代码(C),布布扣,bubuko.com
原文地址:http://blog.csdn.net/caroline_wendy/article/details/36178707