-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgcdofstrings.py
More file actions
63 lines (29 loc) · 993 Bytes
/
gcdofstrings.py
File metadata and controls
63 lines (29 loc) · 993 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# String GCD
# Given two strings, P and Q, your task is to find the largest common divisor string S, such that both P and Q are divisible by S. In other words, there exists a string 'S' for which P = S + S + ... + S and Q = S + S + ... + S. If such a string S exists, output the largest possible S, otherwise, print -1.
# Note: A string X is divisible by string Y if and only if X can be obtained by concatenating Y with itself one or more times.
# Input Format
# The first line of input contains the string P. The Second line of input contains string Q.
# Output Format
# Print the largest string S.
# Constraints
# 1 ≤ len(P), len(Q) ≤ 1000
# 'A' <= P[i],Q[i] <= 'Z'
# Example
# Input
# ABABAB
# ABAB
# Output
# AB
# Explanation
# Self Explanatory
def gcd(p,q):
if p+q!=q+p:
return -1
import math
gcd_len=math.gcd(len(p),len(q))
gcd_str=p[:gcd_len]
return gcd_str
p=input().strip()
q=input().strip()
res=gcd(p,q)
print(res)