poj1338 Ugly Numbers (ugly number simulation)

Source: Internet
Author: User
Tags min


Description

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

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

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

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

Input and Output

There is no. input to the program. Output should consist of a single line as shown below, with <number> replaced by the number computed.

Sample Output

The "th ugly number is <number>.

Idea: Use an array of length 1500 to store these numbers, and another three cursors x, Y, Z;

A[1]=1,x=y=z=1, representing the first number as 1, after which the number is obtained by multiplying the number of 2,3,5,

Then x, Y, z represent a[x],a[y],a[z] can be multiplied by 2,3,5 to get a new number, I increment, each fetch 2*a[x], 3*a[y], 5*a[z]

A[i], the corresponding x (or y,z) can be shifted to the right, of course, if the original 3*2 obtained 6, then 2*3 can also get 6,

Therefore, it is possible that both X and y need to increment.

#include <iostream>
using namespace std;
int min (int a, int b, int c)
{
  return min (a,min (b,c));
}
int main ()
{
  int a[1517];
  int x, y, z, i;
  x = y = z = 1, a[1] = 1;
  for (i = 2; I <=; i++)
  {
    A[i] = min (2*a[x],3*a[y],5*a[z]);
    if (a[i] = = 2*a[x])
    x + +;
    if (a[i] = = 3*a[y])
    y++;
    if (a[i] = = 5*a[z])
    z++;
  }
  int n;
  while (CIN >> n && N)
  {
    cout<<a[n]<<endl;
  }
  return 0;
}


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.