[解題報告]136 - Ugly Numbers


 

 Ugly Numbers 

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

 

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

 

 

shows the first 11 ugly numbers. By convention, 1 is included.

 

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

 

Input and Output

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

 

Sample output

The 1500'th ugly number is <number>.

 

 

記住題目對丑陋數的定義是其基本因子有且只能有2,3,5組成,就是說2*3*5*7=210就不是丑陋數

那么如何得出丑陋數數列?

要得出第N項,就得在前N-1項中掃描,把所有的N-1項乘以2,3,5.然后乘完得到的結果比N-1大且最小的那個就是N

#include<stdio.h>
int main()
{
  int ugly_number[1505] = {1};
  int n2=0,n3=0,n5=0;
  int i;
  for(i=1;i<1500;i++)
  {
    for(;n2<i;n2++)
      if(ugly_number[n2]*2>ugly_number[i-1]) break;
    for(;n3<i;n3++)
      if(ugly_number[n3]*3>ugly_number[i-1]) break;
    for(;n5<i;n5++)
      if(ugly_number[n5]*5>ugly_number[i-1]) break;
    ugly_number[i]=min(ugly_number[n2]*2,ugly_number[n3]*3);
    ugly_number[i]=min(ugly_number[i],ugly_number[n5]*5);
  }

  printf("The 1500'th ugly number is %d.\n",ugly_number[1499]);
  return 0;
}
int min(int a,int b)
{
    return a>b?b:a;
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM