C/C++编程学习 - 第22周 ⑤ 倍数的个数

题目链接

题目描述

读入N,求出1…N的范围内所有2或3或5的倍数一共有多少个?

Input
输入一个数N

Output
输出一个数,表示这样的数的个数

Sample Input

10

Sample Output

8

思路

从1循环到n,看看有多少个数是2的倍数或3的倍数或5的倍数,如果是,则计数器+1,最后输出计数器的值。

C++代码:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
	int n;
	while(cin >> n)
	{
    
    
		int ans = 0;
		for(int i = 1; i <= n; i++)
			if(i % 2 == 0 || i % 3 == 0 || i % 5 == 0) ans++;
		cout << ans << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44826711/article/details/113572611