H.爱出难题的F老师
== Description ==
有一个序列1,12,123,1234,…,12345678910, … ,先给出一整数n,问这个序列前n项中有多少项可以整除3。Input
一个整数n(1<=n<=2^31-1)Output
输出这个序列前n项中整除3的项数
Sample Input4
Sample Output
2
Hint
%20的数据n<=100
%60的数据n<=1000000
%100的数据n<=2^31-1
如果卡题了,不妨换道题试试?思路
我们应该知道,一个数能整除 3 的充分必要条件是它的每一位的数字的和是能整除 3 的
观察所给的序列:1,12,123,1234,12345,123456,…
每一位数字的和依次为 1,3,6,10,15,21,…
如果对 3 取余,那就是 1,0,0,1,0,0,…
为什么呢?
因为该序列每一项的数字和依次是前一项增加1,2,3,4,5,6,7,8,9,10,11,12,13,14,...
对三取余则为 1,2,0,1,2,0,1,2,0,…如此循环
因此该序列从第一项开始以三项为循环节,第一项除以 3 余 1,后两项能整除 3 那么该序列前 n 项能整除 3 的项数为n −⌊(𝑛+2) 3 ⌋个
注意数据范围是 n<=231 − 1,所以用这个公式需要开 long long 以防止 n+2 爆 int 如果找规律可以发现答案也是[𝑛/3]∗2 +(𝑛%3 == 2)
【源代码】
#include<iostream>
using namespace std;
#include<cstdio>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<string>
#include<set>
#include<climits>
#include<cmath>
#include<utility>
#include<algorithm>
#define LL long long
int main()
{
int n;
int ans;
cin >> n;
ans=n/3*2+(n%3==2);
cout << ans;
return 0;
}