科学家正在计划利用 行星上的一个研究模块进行一项重要的测量实验,测量共分为两次进行。
因为宇宙中有多种不确定因素,科学家们已经确定了最佳测量的时间在 l 到 r 范围内。
测量的要求是两次测量的间隔时间必须是 a 的倍数,现在请你帮助科学家计算测量方式的数量。
即有多少对测量时间整数 i 和 j 满足 l <= i < j <= r ,并且 j-i 是 a 的倍数。
进阶:空间复杂度
,时间复杂度 )
科学家正在计划利用 行星上的一个研究模块进行一项重要的测量实验,测量共分为两次进行。
因为宇宙中有多种不确定因素,科学家们已经确定了最佳测量的时间在 l 到 r 范围内。
测量的要求是两次测量的间隔时间必须是 a 的倍数,现在请你帮助科学家计算测量方式的数量。
输入共三行,从上到下三个数字分别代表
在一行中输出测量方式的数量
1 5 2
4
(1,3)、(1,5)、(2,4)和(3,5)共4个
4 9 6
0
一个能满足的都没有
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int l = Integer.parseInt(br.readLine()); int r = Integer.parseInt(br.readLine()); int a = Integer.parseInt(br.readLine()); int n = r - l; long count = 0; for(int i = 1; i <= n / a; i++){ count += n - i*a + 1; // 窗口大小为i*a时,能够滑出的窗口数 } System.out.println(count); } }后来发现评论区大佬们把这个求和过程写成一个统一的公式了,妙哉妙哉!
Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); int temp; int count = 0; for (int i = a; i < b ;i++) { for (int j = b;j > i;j--){ if (j==i) continue; temp = (j-i)%c; if (temp == 0){ count++; } } } System.out.println(count);
#include <vector> #include <iostream> long result = 0; void calcuate(long l, long r, long a, long multiplyNum){ if(r - l >= a * multiplyNum) { result += (r - l - a* multiplyNum) + 1; } } int main(){ long l; std::cin >> l; long r; std::cin >> r; long a; std::cin >> a; long multiply = 1; while(a * multiply <= (r - l)){ calcuate(l ,r ,a, multiply); multiply++; } std::cout << result << std::endl; return 0; }
import java.io.*; public class Main{ public static void main(String[] args) throws IOException{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); long l = Integer.parseInt(bf.readLine()); long r = Integer.parseInt(bf.readLine()); long a = Integer.parseInt(bf.readLine()); long count = 0; long x = (r - l) / a; long y = (r - l) % a; count = x*(1 + y); //其余的等差数列求和 if(x > 1){ long n = x - 1; count += a*(n + 1)*n/2; } System.out.println(count); } }
-(NSInteger)start:(int)l end:(NSInteger)r a:(NSInteger)a{ NSInteger count = 0; for (int i = l; i<r+1; i++) { for (int j = i+1; j<r+1; j++) { if ((j-i)%a == 0) { count += 1; } } } return count; }
}