小Q得到一个神奇的数列: 1, 12, 123,...12345678910,1234567891011...。
并且小Q对于能否被3整除这个性质很感兴趣。
小Q现在希望你能帮他计算一下从数列的第l个到第r个(包含端点)有多少个数可以被3整除。
小Q得到一个神奇的数列: 1, 12, 123,...12345678910,1234567891011...。
并且小Q对于能否被3整除这个性质很感兴趣。
小Q现在希望你能帮他计算一下从数列的第l个到第r个(包含端点)有多少个数可以被3整除。
输入包括两个整数l和r(1 <= l <= r <= 1e9), 表示要求解的区间两端。
输出一个整数, 表示区间内能被3整除的数字个数。
2 5
3
12, 123, 1234, 12345...
其中12, 123, 12345能被3整除。
# coding=utf-8 while 1: try: start,end=map(int,raw_input().split()) count=0 #left=0 def count_3(num): if num%3==0: count=(num/3)*2 elif num%3==1: count=(num/3)*2 elif num%3==2: count=(num/3)*2+1 return count print count_3(end)-count_3(start-1) break except: break 做了很久最后发现蠢是原罪,找规律就好了,三个数中,×√√,所以就不会超出内存。刚开始做的时候一直往求和能否被3整除上面想,即是每逢3清零重新count还是会超出内存只通过百分之七十
1
1%3 = 1
1%3 = 1
12
(1+2)%3 = 0
((1%3)+2%3)%3 = 0
123
(1+2+3)%3 = 0
(((1%3)+2%3)%3+3%3)%3 = 0;
.....
......
// 这样是为了避免数字过大而超出了int范围。
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int count = 0;
int start = sc.nextInt();
int end = sc.nextInt();
int pre = 0;
int i = 0;
//这里用等差数列的求和公式会超出int范围
for(;i<start;i++){
pre+=i%3;
pre%=3;
}
for(;i<=end;i++){
int tempMod = i%3;
pre+=tempMod;
if(pre%3==0){
count++;
}
pre = pre%3;
}
System.out.println(count);
}
}
importjava.util.Scanner; public class Test {public static void main(String[] args) { Scanner sc = newScanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); long result = count(a ,b); System.out.println(result); } private static int count(int start,int end){ if(start > end){ return 0; } intnum =0; for (longi = start-1; i <= end;i++) { longyushu = (((1+i))*i/2)%3; if (yushu==0){ num++; } } return num; } }
package tester0820; import java.util.Scanner; public class Main { private long a; private long b; public Main(long a, long b){ this.a = a; this.b = b; } @SuppressWarnings("resource") public static void main(String[] args){ Scanner in = new Scanner(System.in); long x = in.nextLong(); long y = in.nextLong(); Main m = new Main(x, y); System.out.println(m.test()); } public int test(){ if (a <= b) { int count = 0; for(long i=a; i<=b; i++) { if(i%3 != 1) {count ++; } } return count; } else { return 0; } } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
importjava.util.*;
publicclassMain{
publicstaticvoidmain(String[] args){
Scanner sc = newScanner(System.in);
longa = sc.nextLong();
longb = sc.nextLong();
longcount = 0;
longsum = 0;
for(longk = 1; k <= a; k++){
sum = sum + k;
}
if(sum % 3== 0){
count++;
}
for(longr = a+1; r <= b; r++){
sum = sum + r;
if(sum % 3== 0){
count++;
}
}
System.out.println(count);
}
}
|