import
java.util.*;
import
java.io.*;
import
java.math.*;
public
class
GFG
{
static
int
recursion(ArrayList<Integer> arr1,
ArrayList<Integer> arr2,
int
i,
int
j, Map<ArrayList<Integer>,
Integer> dp)
{
if
(i >= arr1.size() || j >= arr2.size())
return
0
;
ArrayList<Integer> key =
new
ArrayList<>();
key.add(i);
key.add(j);
if
(arr1.get(i) == arr2.get(j))
return
1
+ recursion(arr1, arr2,
i +
1
, j +
1
,
dp);
if
(dp.get(key) != dp.get(dp.size()-
1
))
return
dp.get(key);
else
dp.put(key,Math.max(recursion(arr1, arr2,
i +
1
, j, dp),
recursion(arr1, arr2, i,
j +
1
, dp)));
return
dp.get(key);
}
static
ArrayList<Boolean> primegenerator(
int
n)
{
int
cnt =
0
;
ArrayList<Boolean> primes =
new
ArrayList<>();
for
(
int
i =
0
; i < n +
1
; i++)
primes.add(
true
);
int
p =
2
;
while
(p * p <= n)
{
for
(
int
i = p * p; i <= n; i += p)
primes.set(i,
false
);
p +=
1
;
}
return
primes;
}
static
int
min_element(ArrayList<Integer> al)
{
int
min = Integer.MAX_VALUE;
for
(
int
i =
0
; i < al.size(); i++)
{
min=Math.min(min, al.get(i));
}
return
min;
}
static
int
max_element(ArrayList<Integer> al)
{
int
max = Integer.MIN_VALUE;
for
(
int
i =
0
; i < al.size(); i++)
{
max = Math.max(max, al.get(i));
}
return
max;
}
static
int
longestCommonSubseq(ArrayList<Integer> arr1,
ArrayList<Integer> arr2)
{
int
min1 = min_element(arr1);
int
min2 = min_element(arr2);
int
max1 = max_element(arr1);
int
max2 = max_element(arr2);
ArrayList<Boolean> a = primegenerator(max1);
ArrayList<Boolean> b = primegenerator(max2);
ArrayList<Integer> finala =
new
ArrayList<>();
ArrayList<Integer> finalb =
new
ArrayList<>();
Map<ArrayList<Integer>,Integer> dp =
new
HashMap <ArrayList<Integer>,Integer> ();
for
(
int
i = min1; i <= max1; i++)
{
if
(arr1.contains(i)
&& a.get(i) ==
true
)
finala.add(i);
}
for
(
int
i = min2; i <= max2; i++)
{
if
(arr2.contains(i)
&& b.get(i) ==
true
)
finalb.add(i);
}
return
recursion(finala, finalb,
0
,
0
, dp);
}
public
static
void
main(String args[])
{
int
a1[] = {
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
};
int
a2[] = {
2
,
5
,
6
,
3
,
7
,
9
,
8
};
ArrayList<Integer> arr1 =
new
ArrayList<Integer>();
for
(
int
i =
0
; i < a1.length; i++)
arr1.add(a1[i]);
ArrayList<Integer> arr2 =
new
ArrayList<Integer>();
for
(
int
i =
0
; i < a2.length; i++)
arr2.add(a2[i]);
System.out.println(longestCommonSubseq(arr1, arr2));
}
}