OpenJudge NOI 1.5 编程基础之循环控制(41-45题)C++ 解题思路

续上一篇文章

https://blog.csdn.net/leleprogrammer/article/details/127164315https://blog.csdn.net/leleprogrammer/article/details/127164315剩下最后5道题,继续鸭~~


目录

41 数字统计

42 画矩形

43 质因数分解

44 第n小的质数

45 金币


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章的所有题目就这样告一段落啦!!

喜欢就关注一下吧~~~ 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值