Ugly Numbers

来源:互联网 发布:office使用技巧软件 编辑:程序博客网 时间:2024/05/19 15:43

1525 Ugly Numbers

时间限制:1000MS  内存限制:10000K
提交次数:0 通过次数:0

题型: 外判编程题   语言: C++

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. 

参考于:http://blog.163.com/xiaoy2002@126/blog/static/67979534200992574154434/
思路:丑数肯定是有2、3、5这3个数的乘积,设置了3个变量, 2*a[m2]、3*a[m3]、5*a[m5]取他们中的最小值作为下一个丑数的值,并把相应的变量值加一(m2或m3或m5)

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <math.h>int main(){    int a[1510];    //memset(a,-1,sizeof(a));//初始化    a[0] =1;    int temp=1;    int m2=0,m3=0,m5=0;    int input;    for(int i=1;i<1500;i++)    {        temp = 2*a[m2] > 3*a[m3] ? 3*a[m3] : 2*a[m2];        temp = temp > 5*a[m5] ? 5*a[m5] : temp;        if(temp == 2*a[m2])            m2++;        if(temp == 3*a[m3])            m3++;        if(temp == 5*a[m5])            m5++;        a[i] = temp;    }    scanf("%d",&input);    while(input>0)    {        printf("%d\n",a[input - 1]);        scanf("%d",&input);    }    return 0;}


0 0
原创粉丝点击