1

我是竞争性编程世界的新手,我遇到了一个问题,它试图计算仅包含数字的大字符串的子字符串数。当我尝试在 scorify 平台上运行程序时,它给了我 TimeLimitExceeded 错误。所以如果他们对最小化代码复杂性有任何帮助,我会很高兴

import java.util.Scanner;
import java.math.BigInteger;
public class test {

coprime 是检测两个数是否互质的方法。

private static Boolean coprime(long a, long b) {
    long t;
    while(b!=0){
        t = b;
        b = a%b;
        a = t;
    }
    if(a==1)
        return true;

    return false;
}

我们的主要:)

public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    //t is the number of test cases
    int t =sc.nextInt();
    String s;
    // n is the length of the string that we are going to scan .
    int n;
    //subs is the number of substrings found .
    int subs;
    // m is the long that we are going to compare the substrings with .
    long m;
    for(int i=0;i<t;i++){
        subs = 0;
        n=sc.nextInt();
        m=sc.nextLong();
        sc.nextLine();
        s = sc.nextLine();
        // I separated the cases of the length of s to optimize a little bit because BigIntegers are pain on the memory i think
        //case 1: if the string(number s) entered is greater then the long max value (not so specific)
        if(s.length()>=19){
        BigInteger a;
        // looping through all the substrings
        for(int j=0;j<n;j++){
            for(int p=j;p<n;p++){
                a = new BigInteger(s.substring(j,p+1));
                if(a.gcd(BigInteger.valueOf(m)).compareTo(BigInteger.ONE)==0){
                    subs++;
                }
            }
        }

    }
        // case 2 : if the string(number entered is in the range of long numbers.
    else{
        for(int j=0;j<n;j++){
            for(int p=j;p<n;p++){
                if(coprime(m,Long.parseLong(s.substring(j,p+1)))){
                    subs++;
                }
            }
        }
    }
        //printing the number of substrings.
        System.out.println(subs);
    }
    }

注:输入规格:

输入的第一行包含测试用例的数量 T (1 ≤ T ≤ 10)。

每个测试用例的第一行包含两个整数:N (1 ≤ N ≤ 1000)、字符串的长度和 M (1 ≤ M ≤ 1000000000)。

第二行包含一个长度为 N 的字符串 S。保证 S 只包含数字。

例子:

输入 :

1

10 324567

9207289341

输出 :

40

还:

如果您有关于组织我的代码的说明,我将不胜感激

谢谢你 。

对于那些提出问题的人。

问题 C. 互质子串

如果两个正整数的最大公约数等于 1,则称它们是互质数。现在给定一串数字 S 和一个整数 M,我们感兴趣的是计算 S 的互质数子串的数量与 M。

输入规格:

输入的第一行包含测试用例的数量 T (1 ≤ T ≤ 10)。

每个测试用例的第一行包含两个整数:N (1 ≤ N ≤ 1000)、字符串的长度和 M (1 ≤ M ≤ 1000000000)。

第二行包含一个长度为 N 的字符串 S。保证 S 只包含数字。

输出规格:

对于每个测试用例,在一行上打印 S 的与 M 互质的子串的数量。

标准输入

这是标准输入的内容。

1 10 324567 9207289341
标准输出

您的解决方案应该会产生类似的结果。

40

4

0 回答 0