N - Ugly Numbers

来源:互联网 发布:网络语言我都快长草了 编辑:程序博客网 时间:2024/05/23 14:18

N - Ugly Numbers
Time Limit:1000MS Memory Limit:10000KB 64bit IO Format:%lld & %llu
Submit

Status
Description
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, …
shows the first 10 ugly numbers. By convention, 1 is included.
Given the integer n,write a program to find and print the n’th ugly number.
Input
Each line of the input contains a postisive integer n (n <= 1500).Input is terminated by a line with n=0.
Output
For each line, output the n’th ugly number .:Don’t deal with the line with n=0.
Sample Input
1
2
9
0
Sample Output
1
2
10

#include<stdio.h>#define min(a,b) (a<b?a:b)int main(){    int pos2=1,pos3=1,pos5=1;    int ans[1501];    ans[1]=1;    for(int i=2;i<=1500;i++)    {        int v2=ans[pos2]*2;        int v3=ans[pos3]*3;        int v5=ans[pos5]*5;        ans[i]=min(min(v2,v3),v5);        if(ans[i]==v2)pos2++;        if(ans[i]==v3)pos3++;        if(ans[i]==v5)pos5++;    }    int n;    while(scanf("%d",&n)&&n)    printf("%d\n",ans[n]);}
0 0
原创粉丝点击