Programming algorithms-Number ugly code (C)

Source: Internet
Author: User

number Ugly Code (C)


This address: Http://blog.csdn.net/caroline_wendy


Title: We refer to only the numbers of factors 2, 3 and 5 as ugly numbers. Find the 5th ugly number in order from small to large.


The ability to set an array including the desired number of ugly , in turn, multiplied by 2, multiplied by 3, multiplied by the smallest number of 5, and finally returned the result.

If the 5th ugly number is 5, such as 1, 2, 3, 4 (2*2), 5 are ugly numbers.


Code:

/* * 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];p uglynumbers[0] = 1;int Nextug Lyindex = 1;int* PMultiply2 = puglynumbers;int* PMultiply3 = puglynumbers;int* pMultiply5 = Puglynumbers;while (nextuglyin Dex < index) {int min = min (*pmultiply2*2, *pmultiply3*3, *pmultiply5*5);p Uglynumbers[nextuglyindex] = Min;while (*PMU Ltiply2*2 <= Puglynumbers[nextuglyindex]) ++pmultiply2;while (*pmultiply3*3 <= PUglyNumbers[nextUglyIndex]) + + Pmultiply3;while (*pmultiply5*5 <= puglynumbers[nextuglyindex]) ++pmultiply5;++nextuglyindex;} int ugly = puglynumbers[nextuglyindex-1];d elete[] Puglynumbers;return ugly;} int main (void) {int num = 5;    int result = Getuglynumber (num);    printf ("result =%d\n", result); return 0;}

Output:

result = 5







Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

Programming algorithms-Number ugly code (C)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.