Skip to content

Instantly share code, notes, and snippets.

@chermehdi
Created October 7, 2017 09:43
Show Gist options
  • Save chermehdi/7551622bf86bd3099ec21e681f9d94e4 to your computer and use it in GitHub Desktop.
Save chermehdi/7551622bf86bd3099ec21e681f9d94e4 to your computer and use it in GitHub Desktop.
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* @author MaxHeap
*/
public class CoprimeSubstrings {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CoprimeSubstrings solver = new CoprimeSubstrings();
solver.solve(1, in, out);
out.close();
}
static class CoprimeSubstrings {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
long m = in.nextLong();
String s = in.next();
ArrayList<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
long counter = 0;
for (int j = i; j < n; j++) {
counter = counter * 10 + (s.charAt(j) - '0');
counter %= m;
list.add(counter);
}
}
int ans = 0;
for (long temp : list) {
if (Utils.gcd(temp, m) == 1) ans++;
}
out.println(ans);
}
}
}
static class Utils {
public static long gcd(long a, long b) {
if (b != 0)
return gcd(b, a % b);
return a;
}
}
static class FastReader {
BufferedReader reader;
StringTokenizer st;
public FastReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String line = reader.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment