续上一篇文章
目录
41 数字统计
#include <iostream>
using namespace std;
int main() {
int l,r,result=0;
cin>>l>>r;
for (int i=l;i<=r;++i) {
int i2=i;
while (true) {
int w=i2%10;
i2/=10;
if (w==2) {
result++;
}
if (i2==0) {
break;
}
}
}
cout<<result;
return 0;
}
又是一道分解数位的题~~~~
42 画矩形
#include <iostream>
using namespace std;
int main() {
short w,h,a;
char c;
cin>>h>>w>>c>>a;
a=(bool)a;
for (int i=1;i<=h;++i) {
for (int j=1;j<=w;++j) {
if ((a)||((!a)&&(i==1||i==h||j==1||j==w)))
cout<<c;
else
cout<<" ";
}
cout<<endl;
}
return 0;
}
这道题仿佛又回归输入输出那一篇章了~~~
43 质因数分解
#include <bits/stdc++.h>
using namespace std;
int main() {
int n,z=0;
cin>>n;
for (int i=2;i<=sqrt(n);++i) {
bool a=false;
for (int j=2;j<=sqrt(i);++j) {
if (i%j==0) {
a=true;
break;
}
}
if ((!a)&&n%i==0) {
cout<<n/i;
return 0;
}
}
return 0;
}
直接通过开根号对半,减少算法时间, 因为如果不这样写的话,很大几率这样:
这里开根号用到头文件<cmath>,懒得再写一行,直接用万能头文件<bits/stdc++.h>
44 第n小的质数
#include <bits/stdc++.h>
using namespace std;
int main() {
int n,c=0,i=1;
cin>>n;
while (c<n) {
i++;
bool yes=true;
for (int j=2;j<=sqrt(i);++j) {
if (i%j==0) {
yes=false;
break;
}
}
if (yes) {
c++;
}
}
cout<<i;
return 0;
}
这道题同样sqrt对半来算,高效一点
45 金币
#include <iostream>
using namespace std;
int main() {
int d,gold=0,c=0;
cin>>d;
while (d>c) {
c++;
d-=c;
gold+=c*c;
}
if (d>0) {
c++;
gold+=d*c;
}
cout<<gold;
return 0;
}
好啦,这样我们OpenJudge NOI 1.5章的所有题目就这样告一段落啦!!
喜欢就关注一下吧~~~