Lanqiao Cup Provincial Competition 7-day training camp - simple number theory (1)

Lanqiao Cup Provincial Competition 7-day training camp - simple number theory - Lanqiao cloud class

Table of contents

Problem 1: Prime factorization 

topic description

enter description

output description

Input and output samples

operating limit

topic analysis

A template for prime factorization——acquaintance with the sixth question

 topic code

Second question: prime numbers

topic description

enter description

output description

Input and output samples

operating limit

topic analysis

topic code

 Question 3: The nth digit of the decimal

topic description

enter description

output description

Input and output samples

operating limit

topic analysis

Difficulty: How to get the decimal part

 topic code

Question 4: Put the wheat on the chessboard

topic description

operating limit

topic analysis

topic code

Problem 5: Arithmetic Sequence

topic description

enter description

output description

Input and output samples

operating limit

topic analysis

topic code

Topic 6: Counting

Problem Description

answer submission

operating limit

topic analysis

topic code

Question 7: Approximate Numbers

topic description

operating limit

topic analysis

 topic code

Problem 8: Prime Number Splitting

topic description

operating limit

 topic analysis

topic code


Problem 1: Prime factorization 

topic description

Given that a positive integer n is the product of two different prime numbers , try to find the larger prime number.

enter description

The input is only one line, containing a positive integer 6≤n≤2×10^9.

output description

The output is only one line, containing a positive integer p, the larger prime number.

Input and output samples

example

enter

21

output

7

operating limit

  • Maximum running time: 1s
  • Maximum running memory: 128M

topic analysis

/**
* Decomposition of prime factors is only for composite numbers
* First divide the composite number by the smallest prime factor of a composite number, if the resulting number is a prime number, write the composite number multiplication form; *
If it is a composite number, continue According to the original method, until the last is a prime number.
*/

Because the prime factor may be repeated, use while to repeatedly judge the prime factor

A template for prime factorization——acquaintance with the sixth question

 static int judge(int n) {
        int count = 0;
        for (int i = 2; i <= Math.sqrt(n); i++) {
            while (n % i == 0) {
                count++;//质因数+1
                n = n / i;
            }
        }
        if (n > 1) count++;
        return count;
    }

Don't forget the last n>1 case

if (n > 1) count++;

 topic code

import java.util.HashSet;
import java.util.Scanner;

/**
 * 分解质因数只针对合数
 * 先用一个合数的最小质因数去除这个合数,得出的数若是一个质数,就写成这个合数相乘形式;
 * 若是一个合数就继续按原来的方法,直至最后是一个质数 。
 */
public class 质因数分解 {
    public static void main(String[] args) {
        Scanner sca = new Scanner(System.in);
        long n = sca.nextInt();
        HashSet<Long> set = new HashSet<>();
        //已知正整数n 是两个不同的质数的乘积,试求出较大的那个质数。
        //只需要到sqrt(n)即可,因为如果有一个因数大于等于sqrt(n),那么必定有一个因数小于等于sqrt(n)
        for (long i = 2l; i <= Math.sqrt(n); i++)       //分解质因数:从最小的质因数遍历,
        {
            while (n % i == 0)       //因为质因数可能重复,所以应用while,重复判断质因数 9==3*3
            {
                set.add(i);
                n = n / i;           //n改变
            }
        }
        //特别注意最后n%i!=0的时候如果n>1,n也是一个质因数要加上
        //比如 21 = 3 * 7  (21/3==7、7%3!=0)
        if (n > 1) set.add(n);
        
        long max = 0;
        for (Long i : set) {
            if (i > max) max = i;
        }
        System.out.println(max);
    }
}

Second question: prime numbers

topic description

Given a positive integer N, please output the prime numbers within N (not including N) and the number of prime numbers.

enter description

Enter a line containing a positive integer N. 1≤N≤10^3

output description

There are two lines.

Line 11 contains several prime numbers, each two prime numbers are separated by a space, and the prime numbers are output from small to large.

Line 22 contains an integer representing the number of prime numbers up to N.

Input and output samples

example

enter

10

output

2 3 5 7
4

operating limit

  • Maximum running time: 1s
  • Maximum running memory: 128M

topic analysis

Just a judgment prime 

1) Improvement of intuitive judgment method
For each number n, it is not necessary to judge from 2 to n-1. We know that if a number can be factorized, then the two numbers obtained during the decomposition must be one less than or equal to sqrt (n) , one is greater than or equal to sqrt(n), accordingly, the above code does not need to traverse to n-1, just traverse to sqrt(n), because if there is no divisor on the left side of sqrt(n), Then there must be no approximation on the right side.


Original link: https://blog.csdn.net/huang_miao_xin/article/details/51331710

topic code

import java.util.Scanner;

public class 质数 {
    public static void main(String[] args) {
        Scanner sca = new Scanner(System.in);
        int n = sca.nextInt();
        int count =0;
        for (int i = 2; i < n; i++) {
            if (judge(i)) {
                count++;
                System.out.print(i+" ");
            }
        }
        System.out.println();
        System.out.println(count);
    }

    static Boolean judge(int n) {
        if (n<=0){
            return false;
        }
        for (int i = 2; i <=Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }
}

 Question 3: The nth digit of the decimal

topic description

We know that when integers are divided, sometimes finite decimals are obtained, and sometimes infinite recurring decimals are obtained.

If we add an infinite number of zeros to the end of the finite decimals, they have a unified form.

The task of this question is: under the above convention, find the 3-digit number starting from the nth digit after the decimal point in integer division.

enter description

Enter a line of three integers: a b n, separated by spaces. a is the dividend, b is the divisor, and n is the desired decimal position (0<a,b,n<10^9)

output description

Output a row of 3-digit numbers, which means: divide a by b, 3-digit numbers starting from the nth digit after the decimal.

Input and output samples

example

enter

1 8 1

output

125

operating limit

  • Maximum running time: 1s
  • Maximum running memory: 256M

topic analysis

Difficulty: How to get the decimal part

The last three digits of the nth digit, that is, the nth ------ n + 2 digits, turn the part before the n+2th digit (inclusive) into an integer, and then %1000 is the three-digit answer we want , the smallest bit is the n + 2th bit. If you want to turn it into an integer, you need to multiply it by 10n+2, that is, a / b * 10^(n+2) % 1000 is the answer , because the range of n It may be very large, so a fast exponentiation modulo algorithm is needed .

To learn about the fast exponentiation modulo algorithm, see the link below

Blue Bridge Cup--the nth place of decimals in previous test questions (java)_x/d%m=x%(d脳m)/d_code animal also has a dream blog-CSDN blog

 topic code

import java.util.Scanner;

public class 小数第n位 {
    public static void main(String[] args) {
        Scanner sca = new Scanner(System.in);
        double a = sca.nextDouble();
        double b = sca.nextDouble();
        int n = sca.nextInt();
        int temp = (int)Math.floor((a/b)*Math.pow(10,n+2));
        int res = temp%1000;
        System.out.println(res);
    }
}

not perfect code

Question 4: Put the wheat on the chessboard

topic description

This question is a fill-in-the-blank question. After calculating the result, use the output statement in the code to output the filled result.

You must have heard the story. The king admired the minister who invented chess, and asked him what reward he wanted. The minister said: Please put 1 grain of wheat on the first checkerboard, 2 grains of wheat on the second checkerboard, and 4 grains on the third checkerboard. grains of wheat, put 8 grains of wheat on the 4th grid, ... the number of the next grid is twice that of the previous grid , until all the grids are placed (there are 64 grids in chess  ).

The king thought he just wanted a sack of wheat and laughed.

It was impossible to calculate accurately under the conditions at the time, but the estimated result is surprising: even if the whole world is covered with wheat, it will not be enough!

Please use a computer to accurately calculate how many grains of wheat are needed.

operating limit

  • Maximum running time: 1s
  • Maximum running memory: 128M

topic analysis

  1. The maximum range in java is a 64-bit long integer, which is not enough in the title

  2. Using java.math.BigInteger  can be used to represent integers of any size

Two commonly used definition methods
BigInteger a=new BigInteger("123"); //There is no constructor with long parameters, use strings to construct
BigInteger b=BigInteger.valueOf(123);     //Static method, return val corresponding The BigInteger
BigInteger class defines the methods of four arithmetic operations, add, subtract, multiply, divide. When doing operations on BigInteger, only instance methods can be used .
Such as:
a=a.add(b);

topic code

import java.math.BigInteger;
public class 棋盘放麦子 {

    public static void main(String[] args) {
        BigInteger sum = BigInteger.valueOf(1);
        BigInteger add = BigInteger.valueOf(1);
        BigInteger mul = BigInteger.valueOf(2);
        for (int i = 0; i < 63; i++) {
            add = add.multiply(mul);//*2
            sum = sum.add(add);//+
        }
        System.out.print(sum);
    }
}

Problem 5: Arithmetic Sequence

topic description

The math teacher gave Xiao Ming a problem of summing arithmetic progressions. But the careless Xiao Ming forgot part of the series and only remembered N integers.

Now given these N integers, Xiao Ming wants to know how many items are there in the shortest arithmetic sequence containing these N integers?

enter description

The first line of input contains an integer N.

The second line contains N integers A1​,A2​,⋅⋅⋅,AN​. (Note that A1​ ∼ AN​ are not necessarily given in the order of arithmetic progression)

Among them, 2≤N≤10^5, 0≤Ai​≤10e9.

output description

Output an integer representing the answer.

Input and output samples

example

enter

5
2 6 4 10 20

output

10

Example Explanation: The shortest arithmetic sequence containing 2, 6, 4, 10, 20 is 2, 4, 6, 8, 10, 12, 14, 16, 18, 20.

operating limit

  • Maximum running time: 1s
  • Maximum running memory: 256M

topic analysis

Note that when the tolerance is 0 

topic code

import java.util.Arrays;
import java.util.Scanner;

public class 等差数列 {
    public static void main(String[] args) {
        Scanner sca = new Scanner(System.in);
        int n = sca.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = sca.nextInt();
        }
        Arrays.sort(arr);
        int min = Integer.MAX_VALUE;
        for (int i = 1; i < n; i++) {//找最小公差
            if (arr[i] - arr[i - 1] < min) {
                min = arr[i] - arr[i - 1];
            }
        }
        int a = arr[0];
        int count =0 ;
        if (min==0){//公差为0
            System.out.println(arr.length);
            return;
        }
        while (true) {
            if (a > arr[arr.length - 1]) {
                break;
            }
            count++;
            a = a + min;
        }
        System.out.println(count);
    }
}

Topic 6: Counting

Problem Description

Any positive integer greater than 1 can be decomposed into several prime numbers multiplied, for example, 28=2×2×7 is decomposed into three prime numbers multiplied. How many positive integers in the interval [2333333, 23333333] can be decomposed into 12 prime numbers multiplied together ?

answer submission

This is a question of filling in the blanks with the result, you only need to calculate the result and submit it. The result of this question is an integer. Only fill in this integer when submitting the answer. If you fill in the extra content, you will not be able to score.

operating limit

  • Maximum running time: 1s
  • Maximum running memory: 512M

topic analysis

Direct set of prime factorization templates 

 static int judge(int n) {
        int count = 0;
        for (int i = 2; i <= Math.sqrt(n); i++) {
            while (n % i == 0) {
                count++;//质因数+1
                n = n / i;
            }
        }
        if (n > 1) count++;
        return count;
    }

topic code

public class 数数 {
    public static void main(String[] args) {
        int res = 0;
        for (int i = 2333333; i <= 23333333; i++) {
            if (judge(i) == 12) {
                res++;
            }
        }
        System.out.println(res);
    }

    static int judge(int n) {
        int count = 0;
        for (int i = 2; i <= Math.sqrt(n); i++) {
            while (n % i == 0) {
                count++;//质因数+1
                n = n / i;
            }
        }
        if (n > 1) count++;
        return count;
    }
}

Question 7: Approximate Numbers

topic description

This question is a fill-in-the-blank question. After calculating the result, use the output statement in the code to output the filled result.

How many divisors does 1200000 have (only positive divisors are counted).

operating limit

  • Maximum running time: 1s
  • Maximum running memory: 128M

topic analysis

Just note that 1 is also a factor of n (1 is not a prime number)

 topic code

public class 约数个数 {
    public static void main(String[] args) {
        int n = 1200000;
        int count =0;
        for (int i = 1; i <= Math.sqrt(1200000); i++) {
            if (n%i==0){
                count = count+2;
            }
        }
        if (Math.sqrt(n)*Math.sqrt(n)==n){
            count--;
        }
        System.out.println(count);
    }
}

Problem 8: Prime Number Splitting

topic description

This question is a fill-in-the-blank question. After calculating the result, use the output statement in the code to output the filled result.

How many different methods are there to split 20192019 into the sum of several pairwise different prime numbers?

Note that swapping the order counts as the same method, e.g. 2+2017=2019 and 2017+2=2019 count as the same method.

operating limit

  • Maximum running time: 1s
  • Maximum running memory: 128M

 topic analysis

01 backpack problem

Blue Bridge Cup Learning - 01 Backpack_Blue Bridge Cup 01 Backpack_Xiao Lu Xianchong's Blog-CSDN Blog

topic code

// 1:无需package
// 2: 类名必须Main, 不可修改

public class Main {

    static int n = 2500;
    static int[] arr = new int[n];//存放质数
    static long dp[][] = new long[n][n];//记录方案数

    public static void main(String[] args) {
        int cur = 1; //307 2-2019有307个质数
        for (int i = 2; i < 2019; i++) {
            if (ispre(i)) {
                arr[cur++] = i;
            }
        }
        //开始01背包
        dp[0][0] = 1;//容量为0也是一种方案
        for (int i = 1; i < cur; i++) { //[物品]质数个数
            for (int j = 0; j <= 2019; j++) { //[背包容量]最小为0,所以从0开始
                dp[i][j] = dp[i - 1][j];  //不选i的情况,填充上一个
                if (arr[i] <= j) { //是否超过当前背包总容量
                    /**
                     *  按01背包的术语来讲 arr[i]就是存进j背包花费的空间!! 这边价值总和就是2019
                     *  这个状态转移方程 与当前行无关,与上一行有关
                     *  f[ i] [j]=max(f [i−1] [j],f[i−1] [j−c[i]]+w[i])
                     *  这里直接 f[i][j] = f[i-1][j-c[i]]了
                     */
                    dp[i][j] += dp[i - 1][j - arr[i]]; //如果当前能容下i 选第i个数
                    //dp[1][2] += dp[0][0](1) = 2;  dp[1][3] += dp[0][1];
                    //dp[2][5] += dp[1][2](2) = 3
                }
            }
        }
        System.out.println(dp[cur - 1][2019]);
    }

    public static boolean ispre(int n) {
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

}

Guess you like

Origin blog.csdn.net/weixin_61082895/article/details/129853281