Question:
There is sequence 1, 12, 123, 1234, ..., 12345678910, ... . Given first N elements of that sequence. You must determine amount of numbers in it that are divisible by 3.
Input
Input contains N (1<=N<=231 - 1).
Output
Write answer to the output.
Sample Input
4
Sample Output
2
思路:
一开始想分个、十、百、千位。。。来讨论,发现太复杂。
列举N:1-30的情况后发现,完全是一个不能整除,两个能整除,一个不能整除,两个能整除。。。
即每3个有两个而且是011地分布,于是有了公式n = ((N % 3 == 2)? (N/3*2+1): (N/3*2));
问题解决了。
思考了一下后,发现1-9是好理解的,但是有了十位数后边的复杂,但是仔细想想,9到10的变化与0到1的变化是一种效果
因为0到1是mod3结果是0和1,9到10mod3的结果也是0和1;
这就可以理解了,即不管是多少位,n+1 mod 3 的结果比 n mod 3的结果增1
好像也说不清楚。。。大概就是这样的思路吧。反正“一个不能整除,两个能整除,一个不能整除,两个能整除。。。”这种分布是事实。
代码
#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char *argv[])
{
long N,n;
cin >> N;
n = ((N % 3 == 2)? (N/3*2+1): (N/3*2));
cout << n << endl;
return EXIT_SUCCESS;
}