Lanqiao Cup 2023 14th Provincial Competition Real Questions - Square Difference - Solution

Lanqiao Cup 2023 14th Provincial Competition Real Questions-Squared Difference

Time limit: 3s Memory limit: 320MB Submits: 2379 Resolves: 469

Question description

Given L and R, ask how many numbers x in L ≤ x ≤ R satisfy the existence of integers y and z such that x = y2 − z2.

Input format

The input line contains two integers L and R, separated by a space.

Output format

Output a line containing an integer and the number of x's that meet the conditions given in the question.

Sample input

copy

1 5

Sample output

copy

4

hint

1 = 1^2 − 0^2 ;

3 = 2^2 − 1^2 ;

4 = 2^2 − 0^2 ;

5 = 3^2 − 2^2 。

For 40% of the evaluation cases, LR ≤ 5000;

For all evaluation cases, 1 ≤ L ≤ R ≤ 10^9.

[Analysis of ideas]

Summarize the rules of answers in violent attempts

【Code】

import java.util.Scanner;

/**
 * @ProjectName: study3
 * @FileName: Ex1
 * @author:HWJ
 * @Data: 2023/9/16 22:27
 */
public class Ex1 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int L = input.nextInt();
        int R = input.nextInt();
        //System.out.println(getNums2(L, R));
        System.out.println(getNums3(L, R));
    }

    public static int getNums1(int L, int R){
        // 这个方法可行,但是时间复杂度为O(N^2),不满足题目要求
        int s = (R + 1) / 2;
        int e = (int) Math.sqrt(L) + 1;
        int ans = 0;
        boolean[] have = new boolean[R - L + 1];
        for (int i = s; i >= e; i--) {
            for (int j = i - 1; j >= 0; j--) {
                int a = (i + j) * (i - j);
                if (a >= L && a <= R && !have[a - L]) {
                    ans++;
                    have[a - L] = true;
                } else if (a > R) {
                    break;
                }
            }
        }
        return ans;
    }

    public static int getNums2(int L, int R){
        // 通过观察所有可行的x发现 x要么为奇数要么为4的倍数
        int ans = 0;
        for (int i = L; i <= R; i++) {
            if (i % 4 == 0 || i % 2 != 0){
                ans++;
            }
        }
        return ans;
    }

    public static int getNums3(int L, int R){
        // 通过观察所有可行的x发现 x要么为奇数要么为4的倍数
        // 得到这个规律后,可以统计这样的数目应当为 F(R) = R / 4 + (R + 1) / 2;假设 L == 1
        // 所以实际数目应该为F(R) - F(L - 1)

        return (R / 4 + (R + 1) / 2) - ((L - 1) / 4 + (L) / 2);
    }
}

Guess you like

Origin blog.csdn.net/weixin_73936404/article/details/132894089