我们把只包含因子$2$、$3$和$5$的数成为丑数。例如$6$、$8$都是丑数但$14$不是因为它包含因子$7$。习惯上我们把$1$当作是第一个丑数。先定义一个判断丑数的函数利用它输出$1sim 100$之间所有的丑数并统计出个数。c++代码
#include<iostream>
using namespace std;
bool isUgly(int num) {
while(num%2==0) num/=2;
while(num%3==0) num/=3;
while(num%5==0) num/=5;
return num==1;
}
int main() {
int cnt=1; // cnt用于记录丑数的个数,初始值为1
cout<<1<<" "; // 输出第一个丑数1
for(int i=2;i<=100;i++) {
if(isUgly(i)) {
cnt++; // 如果i是丑数,cnt加1
cout<<i<<" "; // 输出i
}
}
cout<<endl<<"共有"<<cnt<<"个丑数。"<<endl; // 输出丑数的个数
return 0;
}
原文地址: https://www.cveoy.top/t/topic/ggPI 著作权归作者所有。请勿转载和采集!