Humble Numbers
原题链接https://vjudge.net/contest/349774#problem/B
寻找只有2,3,5,7为质因数的数
每一个丑数都是由前面的丑数乘以2,3,5,7得到的,
第一个数为1, 1×2,1×3,1×5,1×7;
第二个数为2, 2×2,2×3,2×5,2×7也就是4,6,10,14;
接下来第三个数为3以此类推
再进行排序,即可得到所有的数,关键点在于对于丑数这个概念的理解,当一个数满足他的质因数只有2,3,5,7时,这个数再乘以2,3,5,7,也满足条件。
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
using namespace std;
long long a[10005];
int main()
{
long long n;
long long i,j,z=1;
long long p2=1,p3=1,p5=1,p7=1;//分别记录2,3,5,7,计算到了第几个数,因为每次都只取四个数中最小的一个,剩下的数要当他们成为当前四个数最小的数的时候再加入数组。
a[1]=1;//用数组a来储存已经得到的数
while(z<5843)
{
z++;
a[z]=min(min(2*a[p2],3*a[p3]),min(5*a[p5],7*a[p7]));
if(a[z]==2*a[p2])//判断本次采用的是哪一个数,将他需要乘的数再往后推一个
{
p2++;
}
if(a[z]==3*a[p3])
{
p3++;
}
if(a[z]==5*a[p5])
{
p5++;
}
if(a[z]==7*a[p7])
{
p7++;
}
}
while(~scanf("%lld",&n))
{
if(n==0)
{
break;
}
if(n%10==1&&n%100!=11)//注意1,2,3,的特殊英语格式
{
printf("The %lldst humble number is %lld.\n",n,a[n]);
}
else if(n%10==2&&n%100!=12)
{
printf("The %lldnd humble number is %lld.\n",n,a[n]);
}
else if(n%10==3&&n%100!=13)
{
printf("The %lldrd humble number is %lld.\n",n,a[n]);
}
else
{
printf("The %lldth humble number is %lld.\n",n,a[n]);
}
}
return 0;
}