The ugly Numbers of Geeks face examination questions

Source: Internet
Author: User
Tags count

Ugly Numbers

Ugly numbers are numbers whose only prime factors 2, 3 or 5. The sequence

1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ...

Shows the ugly numbers. By convention, 1 is included.

Write a program to find and print the 150′th ugly number.

Method 1 (Simple)

Nedylko Draganov for suggesting this solution.

Algorithm:

loop for all positive integers until ugly # count is smaller than n, if a integer is ugly than increment ugly Count.

To check if a are ugly, divide the number by greatest divisible powers of 2, 3 and 5, if the number becomes 1 then I T is a ugly number otherwise not.

For example, let us??? Check for/is ugly or not. Greatest divisible power of 2 are 4 after dividing to 4 we get 75. Greatest divisible power of 3 are 3 after dividing to 3 we get 25. Greatest divisible power of 5 was, after dividing and we get 1. Since we get 1 Finally, the ugly is number.

Back to the column page: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/

Here's a simple method with a program that can print all ugly number less than N:

int maxdivide (int num, int div)  
{while  
    (num% div = = 0)  
    {  
        num/= div;  
    }  
    return num;  
}  
     
BOOL isugly (int num)  
{  
    num = maxdivide (num, 2);  
    num = Maxdivide (num, 3);  
    num = maxdivide (num, 5);  
    return num = 1? True:false;  
}  
     
int Getnthuglyno (int n)  
{  
    int c = 0;  
    int i = 0;  
    while (c < n)  
    {  
        if (isugly (++i)) C + +;  
    }  
    return i;  
}  
#include <vector>  
using Std::vector;  
vector<int> Getalluglyno (int n)  
{  
    vector<int> rs;  
    for (int i = 1; I <= n; i++)  
    {  
        if (isugly (i)) rs.push_back (i);  
    }  
    return RS;  
}

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.