题目要求找出给定位置的humble number
所谓humble number即只有质因子2,3,5,7的数
基本思想 dp+打表
#include<iostream>
#define min(a, b) ((a)<(b)?(a):(b))
using namespace std;
int main()
{
long long a[5843]={0, 1};
int p2=1, p3=1, p5=1, p7=1;
for(int i=2; i<5843; i++){
a[i]=min(min(a[p2]*2, a[p3]*3), min(a[p5]*5, a[p7]*7));
if(a[i]==2*a[p2]){
p2++;
}
if(a[i]==3*a[p3]){
p3++;
}
if(a[i]==5*a[p5]){
p5++;
}
if(a[i]==7*a[p7]){
p7++;
}
}
int n;
while(cin >> n, n){
if(n%10==1&&n%100!=11){
cout << "The " << n << "st" << " humble number is " << a[n] << "." << endl;
}
else if(n%10==2&&n%100!=12){
cout << "The " << n << "nd" << " humble number is " << a[n] << "." << endl;
}
else if(n%10==3&&n%100!=13){
cout << "The " << n << "rd" << " humble number is " << a[n] << "." << endl;
}
else{
cout << "The " << n << "th" << " humble number is " << a[n] << "." << endl;
}
}
return 0;
}
踩坑点
1. 序数词命名
2. 对p2, p3, p5, p7的更新,用并行的4个if,这样才是随时更新p的值,不可以使用else if,这样更新是不同步的
原文:https://www.cnblogs.com/ZGCblogs/p/14167323.html