for i in range(int(input())):
    way = input()
    ans = 0
    pt0 = (0, 0)
    tracks = []
    mono_way_lenght = set(way)
    if mono_way_lenght == 1:
        ans = len(way) * 5
    else:
        for direct in way:
            if direct == 'N':
                pt1 = (pt0[0], pt0[1] + 1)
            elif direct == 'S':
                pt1 = (pt0[0], pt0[1] - 1)
            elif direct == 'E':
                pt1 = (pt0[0] + 1, pt0[1])
            elif direct == 'W':
                pt1 = (pt0[0] - 1, pt0[1])

            if (pt0, pt1) in tracks or (pt1, pt0) in tracks:
                ans += 1
            else:
                ans += 5
            tracks.append((pt0, pt1))
            pt0 = pt1

    print(ans)


for i in range(int(input())):
    way = input()
    ans = 0
    pt0 = (0, 0)
    tracks = []
    for direct in way:
        if direct == 'N':
            pt1 = (pt0[0], pt0[1] + 1)
        elif direct == 'S':
            pt1 = (pt0[0], pt0[1] - 1)
        elif direct == 'E':
            pt1 = (pt0[0] + 1, pt0[1])
        elif direct == 'W':
            pt1 = (pt0[0] - 1, pt0[1])

        if (pt0, pt1) in tracks or (pt1, pt0) in tracks:
            ans += 1
        else:
            ans += 5
        tracks.append((pt0, pt1))
        pt0 = pt1

    print(ans)


for i in range(int(input())):
    way = input()
    ans = 0
    pt0 = (0, 0)
    tracks = []
    if len(set(way)) == 1:
        ans = len(way) * 5
    else:
        for direct in way:
            if direct == 'N':
                pt1 = (pt0[0], pt0[1] + 1)
            elif direct == 'S':
                pt1 = (pt0[0], pt0[1] - 1)
            elif direct == 'E':
                pt1 = (pt0[0] + 1, pt0[1])
            elif direct == 'W':
                pt1 = (pt0[0] - 1, pt0[1])

            if (pt0, pt1) in tracks or (pt1, pt0) in tracks:
                ans += 1
            else:
                ans += 5
            tracks.append((pt0, pt1))
            pt0 = pt1

    print(ans)


for i in range(int(input())):
    k=list(input())
    l=[[0,0]]
    x,y,j,s=0,0,0,0
    while j<len(k):
        if k[j]=='N':
            x=x+1

            if [x,y] in l:
                s=s+1
            else:
                s=s+5
                l.append([x,y])
        elif k[j]=="S":
           x=x-1

           if [x,y] in l:
               s=s+1
           else:
               s=s+5
               l.append([x,y])
        elif k[j]=="W":
           y=y+1
           if [x,y] in l:
               s=s+1
           else:
               s=s+5
               l.append([x,y])
        else:
           y=y-1
           if [x,y] in l:
               s=s+1
           else:
               s=s+5
               l.append([x,y])
        j=j+1
    print(s)


for i in range(int(input())):
    k=list(input())
    l=[[0,0,0,0]]
    x,y,j,s=0,0,0,0
    while j<len(k):
        if k[j]=='N':
            x1=x
            y1=y
            x=x+1
        elif k[j]=="S":
            x1=x
            y1=y
            x=x-1
        elif k[j]=="W":
            x1=x
            y1=y
            y=y+1
        else:
            x1=x
            y1=y
            y=y-1

        if [x1,y1,x,y] not in l:
           s=s+5
           l.append([x,y,x1,y1])
           l.append([x1,y1,x,y])
        else:
           s=s+1
        j=j+1
    print(s)


for i in range(int(input())):
    k=list(input())
    l=[[0,0]]
    x,y,j,s=0,0,0,0
    while j<len(k):
        if k[j]=='N':
            x=x+1
        elif k[j]=="S":
           x=x-1
        elif k[j]=="W":
           y=y+1
        else:
           y=y-1

        if [x,y] not in l:
           s=s+5
           l.append([x,y])
        else:
           s=s+1
        j=j+1
    print(s)


for i in range(int(input())):
    k=list(input())
    l=[[0,0]]
    x,y,j,s=0,0,0,0
    while j<len(k):
        if k[j]=='N':
            x=x+1
        elif k[j]=="S":
           x=x-1
        elif k[j]=="W":
           y=y+1
        else:
           y=y-1

        if [x,y] in l:
           s=s+1
        else:
           s=s+5
           l.append([x,y])
        j=j+1
    print(s)


for i in range(int(input())):
    k=list(input())
    l=[0,0]
    x,y,j,s=0,0,0,0
    while j<len(k):
        if k[j]=='N':
            x=x+1
        elif k[j]=="S":
           x=x-1
        elif k[j]=="W":
           y=y+1
        else:
           y=y-1
        if [x,y] in l:
           s=s+1
        else:
           s=s+5
           l.append([x,y])
        j=j+1
    print(s)


for _ in range(int(input())):
    route = input()
    x, y = 0, 0
    done = set()
    secs = 0
    for i in route:
        if i == "E":
            nx = x + 1
            ny = y + 0
        if i == "W":
            nx = x - 1
            ny = y + 0
        if i == "N":
            nx = x + 0
            ny = y + 1
        if i == "S":
            nx = x + 0
            ny = y - 1
        a = (nx, ny, x, y)
        b = (x, y, nx, ny)
        if a in done or b in done:secs += 1
        else:secs += 5
        done.add(a)
        done.add(b)
        x, y = nx, ny
    print(secs)


for _ in range(int(input())):
    route = input()
    x, y = 0, 0
    done = set()
    secs = 0
    for i in route:
        if i == "E":
            nx = x + 1
            ny = y + 0
        if i == "W":
            nx = x - 1
            ny = y + 0
        if i == "N":
            nx = x + 0
            ny = y + 1
        if i == "S":
            nx = x + 0
            ny = y - 1
        a = (nx, ny, x, y)
        b = (x, y, nx, ny)
        if a in done or b in done:secs += 1
        else:secs += 5
        done.add(a)
        done.add(b)
    print(secs)


def answer(s):
    x=0
    y=0
    d={(x,y):1}
    time=0
    for i in range(len(s)):
        if s[i]=="E":
            x+=1
            if (x,y) in d:
                time+=1
            else:
                time+=5
                d[(x,y)]=1
        elif s[i]=="W":
            x-=1
            if (x,y) in d:
                time+=1
            else:
                time+=5
                d[(x,y)]=1

        elif s[i]=="N":
            y+=1
            if (x,y) in d:
                time+=1
            else:
                time+=5
                d[(x,y)]=1
        else:
            y-=1
            if (x,y) in d:
                time+=1
            else:
                time+=5
                d[(x,y)]=1
    return time

t=int(input())
for i in range(t):
    s=input()
    print(answer(s))


def answer(s):
    x=0
    y=0
    d={}
    time=0
    for i in range(len(s)):
        if s[i]=="E":
            k=[x,y]
            t=[x,y]
            x+=1
            k=tuple(k+[x,y])
            t=tuple([x,y]+t)
            if k in d or t in d:
                time+=1
            else:
                time+=5
                d[k]=1
                d[t]=1
        elif s[i]=="W":
            k=[x,y]
            t=[x,y]
            x-=1
            k=tuple(k+[x,y])
            t=tuple([x,y]+t)
            if k in d or t in d:
                time+=1
            else:
                time+=5
                d[k]=1
                d[t]=1

        elif s[i]=="N":
            k=[x,y]
            t=[x,y]
            y+=1
            k=tuple(k+[x,y])
            t=tuple([x,y]+t)
            if k in d or t in d:
                time+=1
            else:
                time+=5
                d[k]=1
                d[t]=1
        elif s[i]=="S":
            k=[x,y]
            t=[x,y]
            y-=1
            k=tuple(k+[x,y])
            t=tuple([x,y]+t)
            if k in d or t in d:
                time+=1
            else:
                time+=5
                d[k]=1
                d[t]=1
    return time

t=int(input())
for i in range(t):
    s=input()
    print(answer(s))


for T in range(int(input())):

    paths = set()
    x_coord = 0
    y_coord = 0
    directions = input()
    time = 0

    for dir in directions:
        if dir == 'N':
            path = (x_coord, y_coord), (x_coord, y_coord + 1)
            y_coord += 1
        elif dir == 'S':
            path = (x_coord, y_coord), (x_coord, y_coord - 1)
            y_coord -= 1
        elif dir == 'E':
            path = (x_coord, y_coord), (x_coord + 1, y_coord)
            x_coord += 1
        elif dir == 'W':
            path = (x_coord, y_coord), (x_coord - 1, y_coord)
            x_coord -= 1
        inv_path = path[1], path[0]
        if path in paths or inv_path in paths:
            time += 1
        else:
            time += 5
            paths.add(path)

    print(time)


for T in range(int(input())):

    paths = set()
    x_coord = 0
    y_coord = 0
    directions = input()
    time = 0

    for dir in directions:
        if dir == 'N':
            path = (x_coord, y_coord), (x_coord, y_coord + 1)
            y_coord += 1
        elif dir == 'S':
            path = (x_coord, y_coord), (x_coord, y_coord - 1)
            y_coord -= 1
        elif dir == 'E':
            path = (x_coord, y_coord), (x_coord + 1, y_coord)
            x_coord += 1
        elif dir == 'W':
            path = (x_coord, y_coord), (x_coord - 1, y_coord)
            x_coord -= 1
        inv_path = path[1], path[0]
        if path in paths or inv_path in paths:
            time += 1
        else:
            time += 5
            paths.add(path)


for _ in range(int(input())):
    x,y = 0,0
    t = 0
    myset = set()
    directions = input()

    for d in directions:
        x2,y2 = x,y
        if d=='N':
            y2+=1
        elif d=='S':
            y2-=1
        elif d=='E':
            x2+=1
        elif d=='W':
            x2-=1

        if (x,y,x2,y2) in myset or (x2,y2,x,y) in myset:
            t += 1
        else:
            t += 5
        myset.add((x,y,x2,y2))
        x,y=x2,y2

    print(t)


for _ in range(int(input())):
    x,y = 0,0
    t = 0
    myset = {(0,0)}
    directions = input()
    for d in directions:
        if d=='N':
            y+=1
            if (x,y) in myset:
                t += 1
            else:
                t += 5
            myset.add((x,y))
        elif d=='S':
            y-=1
            if (x,y) in myset:
                t += 1
            else:
                t += 5
            myset.add((x,y))
        elif d=='E':
            x+=1
            if (x,y) in myset:
                t += 1
            else:
                t += 5
            myset.add((x,y))
        elif d=='W':
            x-=1
            if (x,y) in myset:
                t += 1
            else:
                t += 5
            myset.add((x,y))

    print(t)


def test():
    string = input()
    visited = set([(0, 0)])
    i, j = 0, 0
    d = {"S":(0, -1), "N":(0, 1), "W": (-1, 0), "E": (1, 0)}
    sum_ = 0
    for s in string:
        i += d[s][0]
        j += d[s][1]

        if (i, j) in visited:
            sum_ += 1
        else:
            sum_ += 5

        visited.add((i, j))

    print(sum_)

n = int(input())
for _ in range(n):
    test()


def test():
    string = input()
    visited = set()
    i, j = 0, 0
    d = {"S":(0, -1), "N":(0, 1), "W": (-1, 0), "E": (1, 0)}
    sum_ = 0
    for s in string:
        next_i = i + d[s][0]
        next_j = j + d[s][1]
        sum_ += 1 if (i, j, next_i, next_j) in visited else 5
        visited.add((i, j, next_i, next_j))
        visited.add((next_i, next_j, i, j))
        i = next_i
        j = next_j
    print(sum_)

n = int(input())
for _ in range(n):
    test()


n = int(input())
for i in range(n):
    s = str(input())
    a = 0
    while s.find('NS') + s.find('SN') + s.find('EW') + s.find('WE') != -4:
        while s.find('NS') != -1:
            s = s[:s.find('NS')] + s[s.find('NS') + 2:]
            a += 6
        while s.find('SN') != -1:
            s = s[:s.find('SN')] + s[s.find('SN') + 2:]
            a += 6
        while s.find('EW') != -1:
            s = s[:s.find('EW')] + s[s.find('EW') + 2:]
            a += 6
        while s.find('WE') != -1:
            s = s[:s.find('WE')] + s[s.find('WE') + 2:]
            a += 6
    a += len(s) * 5
    print(a)


from collections import defaultdict
def solve():
    dp = defaultdict(lambda : 5)

    string = input()
    ans = 0
    x = 0
    y = 0
    x1 = 0
    y1 = 0
    for char in string:
        if char == 'N':
            x1 += 1
        elif char == 'S':
            x1 -= 1
        elif char == 'E':
            y1 += 1
        else:
            y1 -= 1

        getValue = dp[(x, y, x1, y1)]
        ans += getValue

        if getValue == 5:
            dp[(x, y, x1, y1)] = 1
            dp[(x1, y1, x, y)] = 1
        x = x1
        y = y1

    del(dp)
    return ans

t = int(input())
for i in range(t):
    print(solve())


from collections import defaultdict
def solve():
    dp = defaultdict(lambda : 5)

    string = input()
    ans = 0
    x = 0
    y = 0
    dp[(x, y)] = 1
    for char in string:
        if char == 'N':
            x += 1
        elif char == 'S':
            x -= 1
        elif char == 'E':
            y += 1
        else:
            y -= 1

        getValue = dp[(x, y)]
        ans += getValue

        if getValue == 5:
            dp[(x, y)] = 1

    return ans

t = int(input())
for i in range(t):
    print(solve())


from collections import defaultdict
def solve():
    dp = defaultdict(lambda : 5)

    string = input()
    ans = 0
    x = 0
    y = 0
    x1 = 0
    y1 = 0
    for char in string:
        if char == 'N':
            x1 += 1
        elif char == 'S':
            x1 -= 1
        elif char == 'E':
            y1 += 1
        else:
            y1 -= 1

        getValue = dp[(x, y, x1, y1)]
        ans += getValue

        if getValue == 5:
            dp[(x, y, x1, y1)] = 1
            dp[(x1, y1, x, y)] = 1
        x = x1
        y = y1

    return ans

t = int(input())
for i in range(t):
    print(solve())


from collections import defaultdict
def solve():
    dp = defaultdict(lambda : 5)

    string = input()
    ans = 0
    x = 0
    y = 0
    x1 = 0
    y1 = 0
    for char in string:
        if char == 'N':
            x1 += 1
        elif char == 'S':
            x1 -= 1
        elif char == 'E':
            y1 += 1
        else:
            y1 -= 1

        path = f'{x}{y}{x1}{y1}'
        path_rev = f'{x1}{y1}{x}{y}'
        getValue = min(dp[path], dp[path_rev])
        ans += getValue

        if getValue == 5:
            dp[path] = 1
            dp[path_rev] = 1
        x = x1
        y = y1

    del(dp)
    return ans

t = int(input())
for i in range(t):
    print(solve())


from collections import defaultdict
def solve():
    dp = defaultdict(lambda : 5)

    string = input()
    ans = 0
    x = 0
    y = 0
    dp[(x, y)] = 1
    for char in string:
        if char == 'N':
            x += 1
        elif char == 'S':
            x -= 1
        elif char == 'E':
            y += 1
        else:
            y -= 1

        getValue = dp[(x, y)]
        ans += getValue

        if getValue == 5:
            dp[(x, y)] = 1
    del(dp)
    return ans

t = int(input())
for i in range(t):
    print(solve())


for _ in range(int(input())):
    s = input()
    l = []
    x, y = 0, 0
    ans = 0
    for i in s:
        prev_x, prev_y = x, y
        if i == 'N':
            y += 1
        elif i == 'S':
            y -= 1
        elif i == 'E':
            x += 1
        elif i == 'W':
            x -= 1
        if (x, y, prev_x, prev_y) in l or (prev_x, prev_y, x, y) in l:
            ans += 1
        else:
            ans += 5
            l.append((prev_x, prev_y, x, y))
    print(ans)


# The (x,y) directions
direct = {'N':(0,1),'S':(0,-1),'W':(-1,0),'E':(1,0) }
def solve(path):
    visited,begin,time = set(),[0,0],0
    visited.add(tuple(begin))
    for p in path:
        nxt = direct[p]
        begin[0]+=nxt[0]; begin[1]+=nxt[1]
        point = tuple(begin)
        if point not in visited:
            time += 5; visited.add(point)
        else:
            time += 1
    print(time)
for _ in range(int(input())):
    solve(input())


# The (x,y) moves
direct = {'N':(0,1),'S':(0,-1),'W':(-1,0),'E':(1,0) }
def solve(path):
    visited,begin,time = set(),[0,0],0
    for p in path:
        # Get the next position
        nxt = direct[p]
        # Specify the edge and be strict with its direction
        interim = (begin[0] + nxt[0], begin[1] + nxt[1])
        interim2 = tuple(begin)
        p1 = min(interim,interim2); p2 = max(interim,interim2)
        edge = (p2[0],p2[1],p1[0],p1[1])
        if edge not in visited:
            time += 5; visited.add(edge)
            begin[0]+=nxt[0]; begin[1]+=nxt[1]
        else: time += 1
    print(time)
for _ in range(int(input())):
    solve(input())


# The (x,y) moves
direct = {'N':(0,1),'S':(0,-1),'W':(-1,0),'E':(1,0) }
def solve(path):
    visited,begin,time = set(),[0,0],0
    for p in path:
        # Get the next position
        nxt = direct[p]
        # Specify the edge and be strict with its direction
        interim = (begin[0] + nxt[0], begin[1] + nxt[1])
        interim2 = tuple(begin)
        p1 = min(interim,interim2); p2 = max(interim,interim2)
        edge = (p2[0],p2[1],p1[0],p1[1])
        if edge not in visited:
            time += 5; visited.add(edge)
        else: time += 1
        begin[0]+=nxt[0]; begin[1]+=nxt[1]
    print(time)
for _ in range(int(input())):
    solve(input())


def rolltime(string):
    time=0
    x=0
    y=0
    aimed_x=0
    aimed_y=0
    visited=set()
    for step in string:
        if step=='N':
            aimed_x=x
            aimed_y=y+1
        if step=='S':
            aimed_x=x
            aimed_y-=1
        if step=='E':
            aimed_y=y
            aimed=x+1
        if step=='W':
            aimed_y=y
            aimed=x-1
        if frozenset({(x,y),(aimed_x,aimed_y)}) in visited:
                time +=1
        else:
            time+=5
            visited.add(frozenset({(x,y),(aimed_x,aimed_y)}))
        x,y=aimed_x,aimed_y
    return(time)
t=int(input())
strings=[]
for i in range(t):
    strings.append(input())
for i in range(t):
    print(rolltime(strings[i]))


def rolltime(string):
    time=0
    x=0
    y=0
    aimed_x=0
    aimed_y=0
    visited=set()
    for step in string:
        if step=='N':
            aimed_x=x
            aimed_y=y+1
        if step=='S':
            aimed_x=x
            aimed_y-=1
        if step=='E':
            aimed_y=y
            aimed_x=x+1
        if step=='W':
            aimed_y=y
            aimed_x=x-1
        if frozenset({(x,y),(aimed_x,aimed_y)}) in visited:
                time +=1
        else:
            time+=5
            visited.add(frozenset({(x,y),(aimed_x,aimed_y)}))
        x,y=aimed_x,aimed_y
    return(time)
t=int(input())
strings=[]
for i in range(t):
    strings.append(input())
for i in range(t):
    print(rolltime(strings[i]))


import sys
import math
from  collections import defaultdict

# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')

def solve(test):
	s = input()
	up, down, left, right = 0, 0, 0, 0
	ans = 0
	rec = {}
	hor, ver = 0, 0
	for i in s:
		og = (hor, ver)
		if i == 'N':
			ver += 1
		elif i == 'S':
			ver -= 1
		elif i == 'E':
			hor += 1
		else:
			hor -= 1
		if (hor, ver, og[0], og[1]) in rec:
			ans += 1
		else:
			rec[(hor, ver, og[0], og[1])] = 1
			rec[(og[0], og[1], hor, ver)] = 1
			ans += 5
	print(ans)

if __name__ == "__main__":
	test_cases = int(input())
	for t in range(1, test_cases + 1):
		solve(t)


import sys
import math
from  collections import defaultdict

# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')

def solve(test):
	s = input()
	up, down, left, right = 0, 0, 0, 0
	ans = 0
	rec = {(0, 0): 1}
	hor, ver = 0, 0
	for i in s:
		if i == 'N':
			ver += 1
		elif i == 'S':
			ver -= 1
		elif i == 'E':
			hor += 1
		else:
			hor -= 1
		if (hor, ver) in rec:
			ans += 1
		else:
			rec[(hor, ver)] = 1
			ans += 5
	print(ans)

if __name__ == "__main__":
	test_cases = int(input())
	for t in range(1, test_cases + 1):
		solve(t)


from collections import defaultdict
mo=[(1,0),(0,1),(-1,0),(0,-1)]
m={'S':0,'N':2,'E':1,'W':3}
t=int(input())

for _ in range(t):
	s=str(input())
	vi=defaultdict()
	vi.clear()
	vi[(0,0)]=True
	ans=0
	now=(0,0)
	for i in s:
		now=(now[0]+mo[m[i]][0],now[1]+mo[m[i]][1])
		if now in vi.keys():
			ans+=1
		else:
			ans+=5
			vi[now]=True
	print(ans)


from collections import defaultdict
mo=[(1,0),(0,1),(-1,0),(0,-1)]
m={'S':0,'N':2,'E':1,'W':3}
t=int(input())
def do(i):
	if i==0:return(2)
	if i==2:return(0)
	if i==1:return(3)
	return(1)

for _ in range(t):
	s=str(input())
	vi=defaultdict(lambda:[False,False,False,False])
	vi.clear()
	ans=0
	now=(0,0)
	for i in s:
		d=do(m[i])
		vi[now][d]=True
		now=(now[0]+mo[m[i]][0],now[1]+mo[m[i]][1])
		if vi[now][m[i]]:
			ans+=1
		else:
			ans+=5
			vi[now][m[i]]=True
	print(ans)


from collections import defaultdict
mo=[(1,0),(0,1),(-1,0),(0,-1)]
m={'S':0,'N':2,'E':1,'W':3}
t=int(input())
def do(i):
	if i==0:return(2)
	if i==2:return(0)
	if i==1:return(3)
	return(1)

for _ in range(t):
	s=str(input())
	vi=defaultdict(lambda:[False,False,False,False])
	vi.clear()
	ans=0
	now=(0,0)
	for i in s:
		d=do(m[i])
		vi[now][d]=True
		now=(now[0]+mo[m[i]][0],now[1]+mo[m[i]][1])
		if vi[now][m[i]]:
			ans+=1
		else:
			ans+=5
			vi[now][d]=True
	print(ans)


# Template 1.0
import sys, re, math
from collections import deque, defaultdict, Counter, OrderedDict
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from heapq import heappush, heappop, heapify, nlargest, nsmallest
def STR(): return list(input())
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def sortListWithIndex(listOfTuples, idx):   return (sorted(listOfTuples, key=lambda x: x[idx]))
def sortDictWithVal(passedDic):
    temp = sorted(passedDic.items(), key=lambda kv: (kv[1], kv[0]))
    toret = {}
    for tup in temp:
        toret[tup[0]] = tup[1]
    return toret
def sortDictWithKey(passedDic):
    return dict(OrderedDict(sorted(passedDic.items())))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def change(X, Y, charac):
    if(charac=='N'):
        Y+=1
    elif(charac=='S'):
        Y-=1
    elif(charac=='W'):
        X-=1
    else:
        X+=1
    return X, Y

def dashed(ch):
    if (ch == 'N'):
        chdash = 'S'
    elif (ch == 'S'):
        chdash = 'N'
    elif (ch == 'E'):
        chdash = 'W'
    else:
        chdash = 'E'
    return chdash

t = INT()

while(t!=0):
    s = input()
    ans = 0
    dic = {}
    x=y=0

    # print(dic)
    for ch in s:
        # print(dic)
        if((x,y) not in dic):
            ans+=5
            dic[(x, y)] = []

            dic[(x, y)].append(ch)

            x, y = change(x, y, ch)
            if((x,y) in dic):
                dic[(x, y)].append(dashed(ch))
            else:
                dic[(x,y)] = []
                dic[(x, y)].append(dashed(ch))
        else:
            if(ch in dic[(x, y)]):
                ans+=1
                x, y = change(x, y, ch)
            else:

                ans+=5

                dic[(x, y)].append(ch)
                x, y = change(x,y,ch)
                if ((x, y) in dic):
                    dic[(x, y)].append(dashed(ch))
                else:
                    dic[(x, y)] = []
                    dic[(x, y)].append(dashed(ch))
    print(ans)

    t-=1


# Template 1.0
import sys, re, math
from collections import deque, defaultdict, Counter, OrderedDict
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from heapq import heappush, heappop, heapify, nlargest, nsmallest
def STR(): return list(input())
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def sortListWithIndex(listOfTuples, idx):   return (sorted(listOfTuples, key=lambda x: x[idx]))
def sortDictWithVal(passedDic):
    temp = sorted(passedDic.items(), key=lambda kv: (kv[1], kv[0]))
    toret = {}
    for tup in temp:
        toret[tup[0]] = tup[1]
    return toret
def sortDictWithKey(passedDic):
    return dict(OrderedDict(sorted(passedDic.items())))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def change(X, Y, charac):
    if(charac=='N'):
        Y+=1
    elif(charac=='S'):
        Y-=1
    elif(charac=='W'):
        X-=1
    else:
        X+=1
    return X, Y
t = INT()

while(t!=0):
    s = input()
    ans = 0
    dic = {}
    x=y=0
    dic[(x,y)] = []
    ch = s[0]
    if (ch == 'N'):
        chdash = 'S'
    elif (ch == 'S'):
        chdash = 'N'
    elif (ch == 'E'):
        chdash = 'W'
    else:
        chdash = 'E'
    dic[(x, y)].append(chdash)
    for ch in s:
        x, y = change(x, y, ch)
        if((x,y) not in dic):

            ans+=5

            dic[(x, y)] = []
            if(ch=='N'):
                chdash = 'S'
            elif(ch=='S'):
                chdash='N'
            elif(ch=='E'):
                chdash='W'
            else:
                chdash='E'
            dic[(x, y)].append(chdash)
        else:
            if(ch in dic[(x, y)]):
                ans+=1
                # x, y = change(x, y, ch)
            else:

                ans+=5
                # x, y = change(x, y, ch)
                if (ch == 'N'):
                    chdash = 'S'
                elif (ch == 'S'):
                    chdash = 'N'
                elif (ch == 'E'):
                    chdash = 'W'
                else:
                    chdash = 'E'
                dic[(x, y)].append(chdash)
    print(ans)

    t-=1


T = int(input())
while T > 0:
    d = {}
    p = input().strip()
    x, y = 0, 0
    ans = 0

    for c in p:
        if c == 'E':
            if d.get((x, y, c)):
                ans += 1
            else:
                ans += 5
                d[(x, y, c)] = True
                d[(x, y + 1, 'W')] = True

                y += 1

        elif c == 'W':
            if d.get((x, y, c)):
                ans += 1
            else:
                ans += 5
                d[(x, y, c)] = True
                d[(x, y - 1, 'E')] = True

                y -= 1

        elif c == 'N':
            if d.get((x, y, c)):
                ans += 1
            else:
                ans += 5
                d[(x, y, c)] = True
                d[(x - 1, y, 'S')] = True

                x -= 1

        elif c == 'S':
            if d.get((x, y, c)):
                ans += 1
            else:
                ans += 5
                d[(x, y, c)] = True
                d[(x + 1, y, 'N')] = True

                x += 1

    print(ans)

    T -= 1


T = int(input())
while T > 0:
    d = {}
    p = input().strip()
    x, y = 0, 0
    ans = 0

    for c in p:
        if c == 'E':
            if d.get((x, y, c)):
                ans += 1
            else:
                ans += 5
                d[(x, y, c)] = True
                d[(x, y + 1, 'W')] = True

            y += 1

        elif c == 'W':
            if d.get((x, y, c)):
                ans += 1
            else:
                ans += 5
                d[(x, y, c)] = True
                d[(x, y - 1, 'E')] = True

            y -= 1

        elif c == 'N':
            if d.get((x, y, c)):
                ans += 1
            else:
                ans += 5
                d[(x, y, c)] = True
                d[(x - 1, y, 'S')] = True

            x -= 1

        elif c == 'S':
            if d.get((x, y, c)):
                ans += 1
            else:
                ans += 5
                d[(x, y, c)] = True
                d[(x + 1, y, 'N')] = True

            x += 1

    print(ans)

    T -= 1


#include <bits/stdc++.h>
#define SYNC ios_base::sync_with_stdio(0);
#define IO STD std_enable = 1; cin.tie(0);
#define STD /*
from sys import (
stdin, stdout, exit as sys_ret)
"""****************************

       Interactive Tasks:

          / Python: /       """
f_input, f_print, f_flush = (
        stdin.readline,
        stdout.write,
        stdout.flush)

"""        / C++ /
       #import <cstdio>
       fflush(stdout);
             or
       #import <iostream>
       cout << endl;

   —————————————————————————
    Don't raise your voice,
    improve your argument.
   —————————————————————————

   cat /dev/ass > /dev/head
            Ctrl+C
   cat /knowledge > /dev/head

                © Jakov Gellert
                        frvr.ru

****************************"""
# */ using namespace std; int
#define boost_stream(); IO SYNC

for _ in range(int(f_input())):
    answer = 0
    current = (0, 0)
    seen = {(0, 0)}
    for i in f_input().replace('\n', ''):
        if i == 'N': current = (current[0], current[1] + 1)
        elif i == 'E': current = (current[0] - 1, current[1])
        elif i == 'W': current = (current[0] + 1, current[1])
        elif i == 'S': current = (current[0], current[1] - 1)
        if current in seen:
            answer += 1
        else:
            answer += 5
            seen.add(current)
    f_print(str(answer) + '\n')


#include <bits/stdc++.h>
#define SYNC ios_base::sync_with_stdio(0);
#define IO STD std_enable = 1; cin.tie(0);
#define STD /*
from sys import (
stdin, stdout, exit as sys_ret)
"""****************************

       Interactive Tasks:

          / Python: /       """
f_input, f_print, f_flush = (
        stdin.readline,
        stdout.write,
        stdout.flush)

"""        / C++ /
       #import <cstdio>
       fflush(stdout);
             or
       #import <iostream>
       cout << endl;

   —————————————————————————
    Don't raise your voice,
    improve your argument.
   —————————————————————————

   cat /dev/ass > /dev/head
            Ctrl+C
   cat /knowledge > /dev/head

                © Jakov Gellert
                        frvr.ru

****************************"""
# */ using namespace std; int
#define boost_stream(); IO SYNC

for _ in range(int(f_input())):
    answer = 0
    current = (0, 0)
    seen = {current}
    for i in f_input().replace('\n', ''):
        if i == 'N': current = (current[0], current[1] + 1)
        elif i == 'E': current = (current[0] + 1, current[1])
        elif i == 'W': current = (current[0] - 1, current[1])
        elif i == 'S': current = (current[0], current[1] - 1)
        if current in seen:
            answer += 1
        else:
            answer += 5
            seen.add(current)
    f_print(str(answer) + '\n')


#include <bits/stdc++.h>
#define SYNC ios_base::sync_with_stdio(0);
#define IO STD std_enable = 1; cin.tie(0);
#define STD /*
from sys import (
stdin, stdout, exit as sys_ret)
"""****************************

       Interactive Tasks:

          / Python: /       """
f_input, f_print, f_flush = (
        stdin.readline,
        stdout.write,
        stdout.flush)

"""        / C++ /
       #import <cstdio>
       fflush(stdout);
             or
       #import <iostream>
       cout << endl;

   —————————————————————————
    Don't raise your voice,
    improve your argument.
   —————————————————————————

   cat /dev/ass > /dev/head
            Ctrl+C
   cat /knowledge > /dev/head

                © Jakov Gellert
                        frvr.ru

****************************"""
# */ using namespace std; int
#define boost_stream(); IO SYNC

GO = {'N': (0, 1), 'S': (0, -1), 'W': (-1, 0), 'E': (1, 0)}

for _ in range(int(f_input())):
    answer = 0
    seen = set()
    x, y = 0, 0
    for char in f_input().replace('\n', ''):
        x1 = x + GO[char][0]
        y1 = y + GO[char][1]
        if (x, y, x1, y1) in seen or (x1, y1, x, y) in seen:
            answer += 1
        else:
            answer += 5
            seen.add((x, y, x1, y1))
        x, y = x1, y1
    f_print(str(answer) + '\n')


t = int(input())
for _ in range(t):
    directions = input()
    x, y = (0, 0)
    m = {}
    m[(x,y)] = 1
    ans = 0
    for d in directions:
        nx, ny = x, y
        if d == 'N':
            ny += 1
        elif d == 'S':
            ny -= 1
        elif d == 'E':
            nx += 1
        elif d == 'W':
            nx -= 1
        if ((x, y), (nx, ny)) in m:
            ans += 1
        else:
            ans += 5
            m[((x,y), (nx, ny))] = 1
            m[((nx, ny), (x, y))] = 1
        x, y = nx, ny
    print(ans)


for i in range(int(input())):
    mp = [[0]*(10**5)]*(10**5)
    cx ,cy = (10**5)//2 , (10**5)//2

    x = input()
    ans = 0

    for i in x:
        if(i is 'N'):
            if(mp[cx][cy+1]):
                ans+=1
            else:
                mp[cx][cy+1] = 1
                ans+=5
            cx,cy = cx,cy+1
        elif(i is 'S'):
            if(mp[cx][cy-1]):
                ans+=1
            else:
                mp[cx][cy-1] = 1
                ans+=5
            cx,cy = cx,cy-1
        elif(i is 'W'):
            if(mp[cx-1][cy]-1):
                ans+=1
            else:
                mp[cx-1][cy] = 1
                ans+=5
            cx,cy = cx-1,cy
        elif(i is 'E'):
            if(mp[cx+1][cy]):
                ans+=1
            else:
                mp[cx+1][cy] = 1
                ans+=5
            cx,cy = cx+1,cy

    print(ans)


#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
import threading
from math import floor
# from bisect import bisect_right
from collections import Counter
from math import gcd

def main():
    for _ in range(int(input())):
        s=input()
        st=set()
        x=y=cnt=0
        for ind,i in enumerate(s):
            # print(st)
            c_x=x
            c_y=y
            if i=='N':
                x+=1
            elif i=='S':
                x-=1
            elif i=='W':
                y+=1
            else:
                y-=1
            if (c_x,c_y,x,y) in st or (x,y,c_x,c_y) in st:
                cnt+=1
            st.add((c_x,c_y,x,y))
            # if (c_x,c_y) in st and (x,y) in st:
            #     cnt+=1
            # else:
            #     st.add((c_x,c_y))
            #     if (ind>0 and sorted(s[ind-1:ind+1]) in [['N','S'],['E','W'] ] ):
            #         cnt+=1

        # print(cnt)
        print(5*len(s)-4*cnt)

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
import threading
from math import floor
# from bisect import bisect_right
from collections import Counter
from math import gcd

def main():
    for _ in range(int(input())):
        s=input()
        st=set()
        x=y=cnt=0
        for ind,i in enumerate(s):
            # print(st)
            c_x=x
            c_y=y
            if i=='N':
                x+=1
            elif i=='S':
                x-=1
            elif i=='W':
                y+=1
            else:
                y-=1
            if (c_x,c_y) in st and (x,y) in st:
                cnt+=1
            else:
                st.add((c_x,c_y))
                if (ind>0 and sorted(s[ind-1:ind+1]) in [['N','S'],['E','W'] ] ):
                    cnt+=1

        # print(cnt)
        print(5*len(s)-4*cnt)

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


for _ in range(int(input())):
	ans,x,y=0,0,0
	s=set()
	for c in input():
		nx,ny=x,y
		if c=='N': ny+=1
		if c=='S': ny-=1
		if c=='W': nx-=1
		if c=='E': nx+=1
		if (x,y,nx,ny) not in s:
			ans+=5;
			s.add((x,y,nx,ny))
			s.add((nx,ny,x,y))
		else: ans+=1
		x,y=nx,ny
	print(ans)


x=int(input())
for _ in range(x):
	y=input()
	z={}
	z[0]=1
	ans=0
	mx=len(y)+1
	i1=0
	j=0
	for i in y:
		if i=='N':
			j=j+1
		elif i=='S':
			j=j-1
		elif i =='W':
			i1=i1+1
		else: i1=i1-1;
		if i1*mx+j not in z:
			z[i1*mx+j]=1
			ans=ans+5
		else: ans=ans+1
	print(ans)


T = int(input())
x_dir = [0, 0, 1, -1]
y_dir = [1, -1, 0, 0]
direction_str = 'NSWE'
direction_map = dict()
oppo = dict()
oppo_str  = 'SNEW'
for i in range(4):
    oppo[direction_str[i]] = oppo_str[i]
for i in range(4):
    direction_map[direction_str[i]] = i
for t in range(T):
    visited = set()
    s = input()
    x = 0
    y = 0
    ans = 0
    for i in s:
        move = direction_map[i]
        x += x_dir[move]
        y += y_dir[move]
        if (x,y, oppo[i]) in visited:
            ans += 1
        else:
            ans += 5
            if x_dir[move] > 0:
                visited.add((x-1,y, 'W'))
                visited.add((x, y, 'E'))
            elif x_dir[move] < 0:
                visited.add((x+1,y,'E'))
                visited.add((x, y, 'W'))
            elif y_dir[move] > 0:
                visited.add((x, y-1, 'N'))
                visited.add((x,y, 'S'))
            else:
                visited.add((x, y+1, 'S'))
                visited.add((x,y, 'N'))
    print(ans)


T = int(input())
x_dir = [0, 0, 1, -1]
y_dir = [1, -1, 0, 0]
direction_str = 'NSWE'
direction_map = dict()
for i in range(4):
    direction_map[direction_str[i]] = i
for t in range(T):
    visited = set([(0,0)])
    s = input()
    x = 0
    y = 0
    ans = 0
    for i in s:
        move = direction_map[i]
        x += x_dir[move]
        y += y_dir[move]
        if (x,y) in visited:
            ans += 1
        else:
            ans += 5
            visited.add((x,y))
    print(ans)


import sys
dir={'N':(0,1),'S':(0,-1),'E':(1,0),'W':(-1,0)}
cin=sys.stdin.buffer.readline
for _ in range(int(cin())):
    s=input()
    ans=0
    d=set()
    x,y=0,0
    for i in s:
        u=x+dir[i][0]
        v=y+dir[i][1]
        if (x,y,u,v) in d or (u,v,x,y) in d:
            ans+=1
        else:
            ans+=5
            d.add((x,y,u,v))
        x,y=u,v
    print(ans)


import sys
dir={'N':(0,1),'S':(0,-1),'E':(1,0),'W':(-1,0)}
cin=sys.stdin.buffer.readline
for _ in range(int(cin())):
    s=input()
    ans=0
    d=set()
    x,y=0,0
    d.add((x,y))
    for i in s:
        x+=dir[i][0]
        y+=dir[i][1]
        if (x,y) in d:
            ans+=1
        else:
            ans+=5
            d.add((x,y))
    print(ans)


test_cases = int(input("Enter the test cases ").strip())
paths = [input().strip() for _ in range(test_cases)]
#path = input("Enter the path ").strip()

total_time =[]

stack = []
time = 0

for path in paths:
    for direc in path:
        if len(stack) == 0:
            stack.append(direc)
            time += 5
        else:
            if((direc == 'N' and stack[-1] == 'S') or (direc == 'S' and stack[-1] == 'N') or (direc == 'W' and stack[-1] == 'E') or (direc == 'E' and stack[-1] == 'W')):
                stack.pop(-1)
                time += 1
            else:
                stack.append(direc)
                time += 5
    total_time.append(time)

print(*total_time, sep = "\n")


test_cases = int(input().strip())

total_time =[]

for case in range(test_cases):

    stack = []
    time = 0
    path = input()

    for _ in tes:
        for direc in path:
            if len(stack) == 0:
                stack.append(direc)
                time += 5
            else:
                if((direc == 'N' and stack[-1] == 'S') or (direc == 'S' and stack[-1] == 'N') or (direc == 'W' and stack[-1] == 'E') or (direc == 'E' and stack[-1] == 'W')):
                    stack.pop(-1)
                    time += 1
                else:
                    stack.append(direc)
                    time += 5
        total_time.append(time)

print(*total_time, sep = "\n")


test_cases = int(input("Enter the test cases ").strip())
paths = [input().strip() for _ in range(test_cases)]
#path = input("Enter the path ").strip()

total_time =[]

stack = []
time = 0

for path in paths:
    for direc in path:
        if len(stack) == 0:
            stack.append(direc)
            time += 5
        else:
            if((direc == 'N' and stack[-1] == 'S') or (direc == 'S' and stack[-1] == 'N') or (direc == 'W' and stack[-1] == 'E') or (direc == 'E' and stack[-1] == 'W')):
                stack.pop(-1)
                time += 1
            else:
                stack.append(direc)
                time += 5
    total_time.append(time)

print(total_time)


test_cases = int(input().strip())
directions = ['N','S','E','W']
total_time =[]

for _ in range(test_cases):

    stack = []
    time = 0
    path = input()

    for direc in path:
        if direc in directions:
            if len(stack) == 0:
                stack.append(direc)
                time += 5
            else:
                if((direc == 'N' and stack[-1] == 'S') or (direc == 'S' and stack[-1] == 'N') or (direc == 'W' and stack[-1] == 'E') or (direc == 'E' and stack[-1] == 'W')):
                    stack.pop(-1)
                    time += 1
                else:
                    stack.append(direc)
                    time += 5
    total_time.append(time)

print(*total_time, sep = "\n")


test_cases = int(input().strip())
directions = ['N','S','E','W']
total_time =[]

for _ in range(test_cases):

    full_path = set()
    prev = (0,0)
    time = 0
    path = input()

    for direc in path:

        if(direc == 'N'):
            curr = (prev[0],prev[1] + 1)
        elif(direc == 'S'):
            curr = (prev[0],prev[1] - 1)
        elif(direc == 'E'):
            curr = (prev[0] + 1,prev[1])
        else:
            curr = (prev[0] - 1,prev[1])

        if (curr+prev in full_path):
            time += 1
        else:
            time += 5

        full_path.add(curr+prev)
        full_path.add(prev+curr)

        prev = curr

    total_time.append(time)

print(*total_time, sep = "\n")


test_cases = int(input().strip())

total_time =[]

for _ in range(test_cases):

    stack = []
    time = 0
    path = input()

    for direc in path:
        if len(stack) == 0:
            stack.append(direc)
            time += 5
        else:
            if((direc == 'N' and stack[-1] == 'S') or (direc == 'S' and stack[-1] == 'N') or (direc == 'W' and stack[-1] == 'E') or (direc == 'E' and stack[-1] == 'W')):
                stack.pop(-1)
                time += 1
            else:
                stack.append(direc)
                time += 5
    total_time.append(time)

print(*total_time, sep = "\n")


for _ in range(int(input())):
  s=input()
  x_y =(0,0)
  cost=0
  dictxy = { }

  for c in s:
    x_ = x_y[0] + cord[c][0]
    y_ = x_y[1] + cord[c][1]

    cost+= min(dictxy.get((x_y[0],x_y[1],x_,y_),5),dictxy.get((x_,y_,x_y[0],x_y[1]),5))

    dictxy[(x_y[0],x_y[1],x_,y_)]=1

    x_y=(x_,y_)

  print(cost)


from collections import defaultdict

for _ in range(int(input())):
    s = input()
    d = defaultdict(int)
    px, py, res = 0, 0, 0

    for x in s:
        if x == 'E':
            nx = px+1
            ny = py
        elif x == 'W':
            nx = px - 1
            ny = py
        elif x == 'N':
            nx = px
            ny = py + 1
        elif x == 'S':
            nx = px
            ny = py - 1

        if ((px, py), (nx, ny)) in d: res+=1
        elif ((nx, ny), (px, py)) in d: res+=1
        else:
            d[((nx, ny), (px, py))] += 1
            d[((px, py), (nx, ny))] += 1
            res+=5
        px, py = nx, ny

    print(res)


from collections import defaultdict

for _ in range(int(input())):
    s = input()
    d = defaultdict(int)
    px, py, res = 0, 0, 0
    d[(0, 0)]+=1

    for x in s:
        if x == 'E':
            nx = px+1
            ny = py
        elif x == 'W':
            nx = px - 1
            ny = py
        elif x == 'N':
            nx = px
            ny = py + 1
        elif x == 'S':
            nx = px
            ny = py - 1
        if (nx, ny) in d: res+=1
        else:
            d[(nx, ny)]+=1
            res+=5
        px, py = nx, ny

    print(res)


#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include <map>
#include <cmath>
#include <algorithm>
#include <sstream>
#include <fstream>
#include <set>
//#include "print.hpp"

using namespace std;

#define all(c) (c).begin(), (c).end()
#define iter(c) __typeof((c).begin())
#define cpresent(c, e) (find(all(c), (e)) != (c).end())
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define tr(c, i) for (iter(c) i = (c).begin(); i != (c).end(); ++i)
#define pb(e) push_back(e)
#define mp(a, b) make_pair(a, b)

typedef long long ll;

const static int inf = 10000000;
const static int mod = 1000000007;

int p[100000];

bool isprime(int n) {
  if(n <= 1) {
    return false;
  }
  if(p[n] != 0) {
    return p[n] == 1;
  }

  for(int i = 2; i*i<=n; ++i) {
    if(n % i == 0) {
      p[n] = -1;
      return false;
    }
  }
  p[n] = 1;
  return true;
}

int d;
int table[5][5];

int getTranspose(int i, int j , int& k, int& l) {
  k = (d-1)-j;
  l = (d-1)-i;
}

int offsets[6];

int memo4[10000];
int memo3[1000][1000];
int memo2[100][100][100];
int memo1[10][10][10][10];

int calc(int depth) {
  if(depth == d) {
    return 1;
  }

  vector<int> keys(depth);
  rep(i, depth) {
    int buf = 0;
    rep(j, d-depth) {
      buf *= 10;
      buf += table[i][((d-1)-depth)-j];
    }
    keys[i] = buf;
  }

  /*
  for(int i = 0; i < d; ++i) {
    rep(j, d) {
      cout << table[i][j] << " ";
    }
    cout << endl;
  }

  cout << "keys : " ;
  rep(i, depth) {
    cout << keys[i] << " ";
  }
  cout << endl;

  cout << "memo : ";
  cout << memo4[keys[0]] << " "
       << memo3[keys[0]][keys[1]] << " "
       << memo2[keys[0]][keys[1]][keys[2]] << " "
       << memo1[keys[0]][keys[1]][keys[2]][keys[3]] <<endl;
  */

  if(depth == 1) {
    if(memo4[keys[0]] != -1) {
      return memo4[keys[0]];
    }
  }else if(depth == 2) {
    if(memo3[keys[0]][keys[1]] != -1) {
      return memo3[keys[0]][keys[1]];
    }
  }else if(depth == 3) {
    if(memo2[keys[0]][keys[1]][keys[2]] != -1) {
      return memo2[keys[0]][keys[1]][keys[2]];
    }
  }else {
    if(memo1[keys[0]][keys[1]][keys[2]][keys[3]] != -1) {
      return memo1[keys[0]][keys[1]][keys[2]][keys[3]];
    }
  }

  int base = 0;
  for(int i = 0; i < d; ++i) {
    base *= 10;
    base += table[depth][(d-1)-i];
  }

  int mx = offsets[d-depth];
  int ans = 0;
  for(int i = 1; i < mx; ++i) {
    if(isprime(base+i)) {
      int buf = i;
      for(int j = 0; j < d-depth; ++j) {
	table[depth][j] = buf % 10;
	int k, l; getTranspose(depth, j, k, l);
	table[k][l] = table[depth][j];
	buf /= 10;
      }

      ans += calc(depth+1);

      for(int j = 0; j < d-depth; ++j) {
	table[depth][j] = 0;
	int k, l; getTranspose(depth, j, k, l);
	table[k][l] = 0;
      }
    }
  }

  if(depth == 1) {
    return memo4[keys[0]] = ans;
  }else if(depth == 2) {
    return memo3[keys[0]][keys[1]] = ans;
  }else if(depth == 3) {
    return memo2[keys[0]][keys[1]][keys[2]] = ans;
  }else {
    return memo1[keys[0]][keys[1]][keys[2]][keys[3]] = ans;
  }
}

int main(){
  int t;
  while(cin >> t){
    memset(p, 0, sizeof(p));
    memset(memo4, -1, sizeof(memo4));
    memset(memo3, -1, sizeof(memo3));
    memset(memo2, -1, sizeof(memo2));
    memset(memo1, -1, sizeof(memo1));

    int base = 1;
    rep(i, 6) {
      offsets[i] = base;
      base *= 10;
    }

    rep(i, t) {
      memset(table, 0, sizeof(table));
      int p; cin >> p;
      int buf = p;
      d = 0;
      while(buf > 0) {
	table[0][d] = buf % 10;
	buf /= 10;
	++d;
      }

      rep(i, d) {
	int k, l; getTranspose(0, i, k, l);
	table[k][l] = table[0][i];
      }
      cout << calc(1) << endl;
    }
  }
  return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;

typedef long long lld;

bool prime[100100];

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    } prime[0] = prime[1] = false;
}

int ord;

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
}

char num[8][8];

lld out = 0;

int amount(int idx=1) {
    if (idx == ord) {
        return 1;
    }
    int mult = 0;
    for (int i=0; i<10; i++) {
        num[idx][idx] = i+'0';
        if (prime[atoi(num[idx])]) {
            mult++;
        }
    }
    return mult*amount(idx+1);
}
void generate(int h, int w) {
    if (h >= ord-1) {
        out += amount();
    }
    else if (w >= ord) {
        generate(h+1, h+2);
    }
    else {
        for (int i=0; i<10; i++) {
            if (w == ord-1 && i%2 == 0) {
                continue;
            }
            num[h][w] = num[w][h] = i+'0';
            generate(h, w+1);
        }
    }
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
    sprintf(num[0], "%d", pi);
    for (int i=0; i<ord; i++) {
        num[i][0] = num[0][i];
        num[i][ord] = '\0';
    }
    out = 0;
        generate(1, 2);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;

typedef long long lld;

bool prime[100100];
int k=0;
int p[100100];
int ptr[100100];
int low[100100];

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=0; i<100100; i++) {
        low[i] = i+1;
    }
    low[100099] = 100099;
    ptr[100099] = 100100;
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            low[i] = i;
            ptr[i] = k;
            p[k++] = i;
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    }
}

int ord;
int pre[6][6];

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
    for (int i=0; i<6; i++) {
        for (int j=0; j<6; j++) {
            pre[i][j] = 0;
        }
    }
}

void fill(int v, int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = v%10;
        v/=10;
    }

}

void unfill(int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = 0;
    }
}

int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

const int TABLESIZE = 1234567;
int cache[6][6][TABLESIZE];

int getDig(int val) {
    int ct = 0;
    while (val) {
        val /= 10;
        ct++;
    }
    return max(ct, 1);
}

unsigned long long hashVal(char *arr) {
    unsigned long long ret = 10000007;
    for (int i=0; i<10; i++) {
        ret = ((ret<<6) + (ret<<16)) - ret + arr[i];
    }
    return ret;
}

int getState() {
    char buff[11];
    buff[0] = pre[1][0];
    buff[1] = pre[2][0];
    buff[2] = pre[2][1];
    buff[3] = pre[3][0];
    buff[4] = pre[3][1];
    buff[5] = pre[3][2];
    buff[6] = pre[4][0];
    buff[7] = pre[4][1];
    buff[8] = pre[4][2];
    buff[9] = pre[4][3];
    unsigned long long ret = hashVal(buff);
    return ret % TABLESIZE;
}

int findlow(int val) {
    if (low[val] == val) {
        return val;
    }
    return low[val] = findlow(low[val]);
}

int ways(int r) {
    if (r == ord) {
        return 1;
    }
    int hashID = getState();
    if (cache[ord][r][hashID]) {
        return cache[ord][r][hashID];
    }
    int ret = 0;
    int prefix = 0;
    for (int i=0; i<r; i++) {
        prefix += pre[r][i] * pow10(ord-i-1);
    }
    int upper = prefix + pow10(ord-r);
    int low = ptr[findlow(prefix)];
    for (int i = low; i<k && p[i] < upper; i++) {
        fill(p[i], r);
        ret += ways(r+1);
        unfill(r);
    }
    return cache[ord][r][hashID] = ret;
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        fill(pi, 0);
        lld out = ways(1);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;

typedef long long lld;

bool prime[100100];
int k=0;
int p[100100];;

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            p[k++] = i;
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    }
}

int ord;
char pre[6][6];

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
    for (int i=0; i<6; i++) {
        for (int j=0; j<6; j++) {
            pre[i][j] = 0;
        }
    }
}

void fill(int v, int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = v%10;
        v/=10;
    }

}

void unfill(int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = 0;
    }
}

int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

const int TABLESIZE = 1234567;
lld cache[6][6][TABLESIZE];

int getDig(int val) {
    int ct = 0;
    while (val) {
        val /= 10;
        ct++;
    }
    return max(ct, 1);
}

lld getState() {
    unsigned long long ret = 10000007;
    ret = ret<<5 ^ pre[1][0];
    ret = ret<<5 ^ pre[2][0];
    ret = ret<<5 ^ pre[2][1];
    ret = ret<<5 ^ pre[3][0];
    ret = ret<<5 ^ pre[3][1];
    ret = ret<<5 ^ pre[3][2];
    ret = ret<<5 ^ pre[4][0];
    ret = ret<<5 ^ pre[4][1];
    ret = ret<<5 ^ pre[4][2];
    ret = ret<<5 ^ pre[4][3];
    return ret % TABLESIZE;
}

lld ways(int r) {
    if (r == ord) {
        return 1;
    }
    lld hashID = getState();
    if (cache[ord][r][hashID]) {
        return cache[ord][r][hashID];
    }
    lld ret = 0;
    int prefix = 0;
    for (int i=0; i<r; i++) {
        prefix += pre[r][i] * pow10(ord-i-1);
    }
    int upper = prefix + pow10(ord-r);
    int *low = lower_bound(p, p+k, prefix);
    for (int i = low-p; i<k && p[i] < upper; i++) {
        fill(p[i], r);
        ret += ways(r+1);
        unfill(r);
    }
    return cache[ord][r][hashID] = ret;
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        fill(pi, 0);
        lld out = ways(1);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;

typedef long long lld;

bool prime[100100];
int k=0;
int p[100100];
int ptr[100100];
int low[100100];

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=0; i<100100; i++) {
        low[i] = i+1;
    }
    low[100099] = 100099;
    ptr[100099] = 100100;
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            low[i] = i;
            ptr[i] = k;
            p[k++] = i;
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    }
}

int ord;
char pre[6][6];

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
    for (int i=0; i<6; i++) {
        for (int j=0; j<6; j++) {
            pre[i][j] = 0;
        }
    }
}

void fill(int v, int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = v%10;
        v/=10;
    }

}

void unfill(int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = 0;
    }
}

int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

const int TABLESIZE = 1234567;
int cache[6][6][TABLESIZE];

int getDig(int val) {
    int ct = 0;
    while (val) {
        val /= 10;
        ct++;
    }
    return max(ct, 1);
}

lld getState() {
    unsigned long long ret = 10000007;
    ret = (ret<<5 ^ pre[1][0]) | ret;
    ret = (ret<<5 ^ pre[2][0]) | ret;
    ret = (ret<<5 ^ pre[2][1]) | ret;
    ret = (ret<<5 ^ pre[3][0]) | ret;
    ret = (ret<<5 ^ pre[3][1]) | ret;
    ret = (ret<<5 ^ pre[3][2]) | ret;
    ret = (ret<<5 ^ pre[4][0]) | ret;
    ret = (ret<<5 ^ pre[4][1]) | ret;
    ret = (ret<<5 ^ pre[4][2]) | ret;
    ret = (ret<<5 ^ pre[4][3]) | ret;
    return ret % TABLESIZE;
}

int findlow(int val) {
    if (low[val] == val) {
        return val;
    }
    return low[val] = findlow(low[val]);
}

int ways(int r) {
    if (r == ord) {
        return 1;
    }
    int hashID = getState();
    if (cache[ord][r][hashID]) {
        return cache[ord][r][hashID];
    }
    int ret = 0;
    int prefix = 0;
    for (int i=0; i<r; i++) {
        prefix += pre[r][i] * pow10(ord-i-1);
    }
    int upper = prefix + pow10(ord-r);
    //int *low = lower_bound(p, p+k, prefix);
    int low = ptr[findlow(prefix)]; // can optmise to O(1) with disjoint set
    for (int i = low; i<k && p[i] < upper; i++) {
        fill(p[i], r);
        ret += ways(r+1);
        unfill(r);
    }
    return cache[ord][r][hashID] = ret;
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        fill(pi, 0);
        lld out = ways(1);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;

typedef long long lld;

bool prime[100100];
int ord;
char num[8][8];
int ct[200100][7];

void insert(int val) {
    char buff[10];
    sprintf(buff, "%.6d", val);
    int lv = strlen(buff);
    for (int i=0; i<6; i++) {
        int o = buff[6-i-1];
        buff[6-i-1] = '1';
        ct[atoi(buff)][i] ++;
        buff[6-i-1] = o;
    }
}

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            insert(i);
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    } prime[0] = prime[1] = false;
}

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
    for (int i=0; i<8; i++) {
        for (int j=0; j<8; j++) {
            num[i][j] = '0';
        }
    }
}

inline int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

int multi=1;
lld out = 0;

void generate(int h) {
    if (h >= ord) {

        out += multi;
        //printf("====\n");
        return;
    }
    else {
        int val = atoi(num[h]);
        int lim = pow10(ord-h-1);
        for (int i=0; i<lim; i++) {
            int o = i;
            if (ct[val+i][ord-h-1]) {
                for (int j=ord-1; j>h; j--) {
                    num[j][h] = '0'+o%10;
                    o/=10;
                }
                /*for (int p=0; p<h; p++) {
                    printf("--");
                }printf("entered as %d with multi %d\n", val+i, ct[val+i][ord-h-1]);*/

                multi *= ct[val+i][ord-h-1];
                generate(h+1);
                multi /= ct[val+i][ord-h-1];
            }
        }
    }

}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        sprintf(num[0], "%d", pi);
        for (int i=0; i<ord; i++) {
            num[i][0] = num[0][i];
            num[i][ord] = '\0';
            num[i][i] = '1';
        }
        out = 0;
        generate(1);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;

typedef long long lld;

bool prime[100100];
int k=0;
int p[100100];
int ptr[100100];
int low[100100];

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=0; i<100100; i++) {
        low[i] = i+1;
    }
    low[100099] = 100099;
    ptr[100099] = 100100;
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            low[i] = i;
            ptr[i] = k;
            p[k++] = i;
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    }
}

int ord;
int use[6];

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
}

int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

int findlow(int val) {
    if (low[val] == val) {
        return val;
    }
    return low[val] = findlow(low[val]);
}

#define mp make_pair

map<pair<int, pair<int, pair<int, int> > >, int > cache;

int ways(int r) {
    if (r == ord) {
        return 1;
    }
    if (cache.count(mp(use[0], mp(use[1], mp(use[2], use[3]))))) {
    return cache[mp(use[0], mp(use[1], mp(use[2], use[3])))];
    }
    int ret = 0;
    int prefix = 0;
    for (int i=0; i<r; i++) {
        prefix = prefix*10 + (use[i]/pow10(ord-r-1))%10;
    }
    prefix*=pow10(ord-r);
    int upper = prefix + pow10(ord-r);
    int low = ptr[findlow(prefix)];
    for (int i = low; i<k && p[i] < upper; i++) {
        use[r] = p[i];
        ret += ways(r+1);
    use[r] = 0;
    }
    return cache[mp(use[0], mp(use[1], mp(use[2], use[3])))] = ret;
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        use[0] = pi;
        lld out = ways(1);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;

typedef long long lld;

bool prime[100100];

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    } prime[0] = prime[1] = false;
}

int ord;

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
}

char num[8][8];

lld out = 0;

int amount(int idx=1) {
    if (idx == ord) {
        return 1;
    }
    int mult = 0;
    for (int i=0; i<10; i++) {
        num[idx][idx] = i+'0';
        if (prime[atoi(num[idx])]) {
            mult++;
        }
    }
    return mult*amount(idx+1);
}
void generate(int h, int w) {
    if (h >= ord-1) {
        out += amount();
    }
    else if (w >= ord) {
        generate(h+1, h+2);
    }
    else {
        for (int i=0; i<10; i++) {
            //if (w == ord-1 && i%2 == 0) {
            //  continue;
            //}
            num[h][w] = num[w][h] = i+'0';
            generate(h, w+1);
        }
    }
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
    sprintf(num[0], "%d", pi);
    for (int i=0; i<ord; i++) {
        num[i][0] = num[0][i];
        num[i][ord] = '\0';
    }
    out = 0;
        generate(1, 2);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>

using namespace std;

typedef long long lld;

bool prime[100100];
int k=0;
int p[100100];;

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            p[k++] = i;
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    }
}

int ord;
int pre[6];

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
    for (int i=0; i<6; i++) {
        pre[i] = 0;
    }
}

void fill(int v, int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i] = pre[i]*10 + v%10;
        v/=10;
    }

}

void unfill(int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i] /= 10;
    }
}

int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

lld ways(int r) {
    if (r == ord) {
        return 1;
    }
    lld ret = 0;
    int prefix = pre[r] * pow10(ord-r);
    int upper = (pre[r]+1) * pow10(ord-r);
    int *low = lower_bound(p, p+k, prefix);
    for (int i = low-p; i<k && p[i] < upper; i++) {
        fill(p[i], r);
        ret += ways(r+1);
        unfill(r);
    }
    return ret;
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        fill(pi, 0);
        lld out = ways(1);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>
#include <hash_set>

using namespace std;

typedef long long lld;

bool prime[100100];
int k=0;
int p[100100];
int ptr[100100];
int low[100100];

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=0; i<100100; i++) {
        low[i] = i+1;
    }
    low[100099] = 100099;
    ptr[100099] = 100100;
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            low[i] = i;
            ptr[i] = k;
            p[k++] = i;
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    }
}

int ord;
int pre[6][6];

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
    for (int i=0; i<6; i++) {
        for (int j=0; j<6; j++) {
            pre[i][j] = 0;
        }
    }
}

void fill(int v, int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = v%10;
        v/=10;
    }

}

void unfill(int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = 0;
    }
}

int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

const int TABLESIZE = 1234567;
int cache[6][6][TABLESIZE];

int getDig(int val) {
    int ct = 0;
    while (val) {
        val /= 10;
        ct++;
    }
    return max(ct, 1);
}

hash<int> H;

int getState() {
    lld buff = pre[1][0];
    buff = 10*buff + pre[2][0];
    buff = 10*buff + pre[2][1];
    buff = 10*buff + pre[3][0];
    buff = 10*buff + pre[3][1];
    buff = 10*buff + pre[3][2];
    buff = 10*buff + pre[4][0];
    buff = 10*buff + pre[4][1];
    buff = 10*buff + pre[4][2];
    buff = 10*buff + pre[4][3];
    lld ret = H(buff);
    return ret % TABLESIZE;
}

int findlow(int val) {
    if (low[val] == val) {
        return val;
    }
    return low[val] = findlow(low[val]);
}

int ways(int r) {
    if (r == ord) {
        return 1;
    }
    //int hashID = getState();
    //if (cache[ord][r][hashID]) {
    //  return cache[ord][r][hashID];
    //}
    int ret = 0;
    int prefix = 0;
    for (int i=0; i<r; i++) {
        prefix += pre[r][i] * pow10(ord-i-1);
    }
    int upper = prefix + pow10(ord-r);
    int low = ptr[findlow(prefix)];
    for (int i = low; i<k && p[i] < upper; i++) {
        fill(p[i], r);
        ret += ways(r+1);
        unfill(r);
    }
    return ret;
    //return cache[ord][r][hashID] = ret;
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        fill(pi, 0);
        lld out = ways(1);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>

using namespace std;

typedef long long lld;

bool prime[100100];
int k=0;
int p[100100];;

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            p[k++] = i;
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    }
}

int ord;
int pre[6];

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
    for (int i=0; i<6; i++) {
        pre[i] = 0;
    }
}

void fill(int v, int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i] = pre[i]*10 + v%10;
        v/=10;
    }

}

void unfill(int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i] /= 10;
    }
}

int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

lld ways(int r) {
    if (r == ord) {
        return 1;
    }
    lld ret = 0;
    int prefix = pre[r] * pow10(ord-r);
    int upper = (pre[r]+1) * pow10(ord-r);
    int *low = lower_bound(p, p+k, prefix);
    for (int i = low-p; i<k && p[i] < upper; i++) {
        fill(p[i], r);
        ret += ways(r+1);
        unfill(r);
    }
    return ret;
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        fill(pi, 0);
        lld out = ways(1);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;

typedef long long lld;

bool prime[100100];

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    } prime[0] = prime[1] = false;
}

int ord;

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
}

char num[8][8];

lld out = 0;

int amount(int idx=1) {
    if (idx == ord) {
        return 1;
    }
    int mult = 0;
    for (int i=0; i<10; i++) {
        num[idx][idx] = i+'0';
        if (prime[atoi(num[idx])]) {
            mult++;
        }
    }
    return mult*amount(idx+1);
}
void generate(int h, int w) {
    if (h >= ord-1) {
        out += amount();
    }
    else if (w >= ord) {
        generate(h+1, h+2);
    }
    else {
        for (int i=0; i<10; i++) {
            if (w==ord-1 && i%2 == 0 && i > 2) {
                continue;
            }
            num[h][w] = num[w][h] = i+'0';
            generate(h, w+1);
        }
    }
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
    sprintf(num[0], "%d", pi);
    for (int i=0; i<ord; i++) {
        num[i][0] = num[0][i];
        num[i][ord] = '\0';
    }
    out = 0;
        generate(1, 2);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;

typedef long long lld;

bool prime[100100];
int k=0;
int p[100100];
int ptr[100100];
int low[100100];

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=0; i<100100; i++) {
        low[i] = i+1;
    }
    low[100099] = 100099;
    ptr[100099] = 100100;
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            low[i] = i;
            ptr[i] = k;
            p[k++] = i;
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    }
}

int ord;
int pre[6][6];

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
    for (int i=0; i<6; i++) {
        for (int j=0; j<6; j++) {
            pre[i][j] = 0;
        }
    }
}

void fill(int v, int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = v%10;
        v/=10;
    }

}

void unfill(int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = 0;
    }
}

int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

const int TABLESIZE = 1234567;
int cache[6][6][TABLESIZE];

int getDig(int val) {
    int ct = 0;
    while (val) {
        val /= 10;
        ct++;
    }
    return max(ct, 1);
}

unsigned long long hashVal(char *arr) {
    unsigned long long ret = 10000007;
    for (int i=0; i<10; i++) {
        ret = ((ret<<5) + ret) + arr[i];
    }
    return ret;
}

int getState() {
    char buff[11];
    buff[0] = pre[1][0];
    buff[1] = pre[2][0];
    buff[2] = pre[2][1];
    buff[3] = pre[3][0];
    buff[4] = pre[3][1];
    buff[5] = pre[3][2];
    buff[6] = pre[4][0];
    buff[7] = pre[4][1];
    buff[8] = pre[4][2];
    buff[9] = pre[4][3];
    unsigned long long ret = hashVal(buff);
    return ret % TABLESIZE;
}

int findlow(int val) {
    if (low[val] == val) {
        return val;
    }
    return low[val] = findlow(low[val]);
}

int ways(int r) {
    if (r == ord) {
        return 1;
    }
    int hashID = getState();
    if (cache[ord][r][hashID]) {
        return cache[ord][r][hashID];
    }
    int ret = 0;
    int prefix = 0;
    for (int i=0; i<r; i++) {
        prefix += pre[r][i] * pow10(ord-i-1);
    }
    int upper = prefix + pow10(ord-r);
    int low = ptr[findlow(prefix)];
    for (int i = low; i<k && p[i] < upper; i++) {
        fill(p[i], r);
        ret += ways(r+1);
        unfill(r);
    }
    return cache[ord][r][hashID] = ret;
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        fill(pi, 0);
        lld out = ways(1);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;

typedef long long lld;

bool prime[100100];
int k=0;
int p[100100];
int ptr[100100];
int low[100100];

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=0; i<100100; i++) {
        low[i] = i+1;
    }
    low[100099] = 100099;
    ptr[100099] = 100100;
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            low[i] = i;
            ptr[i] = k;
            p[k++] = i;
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    }
}

int ord;
char pre[6][6];

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
    for (int i=0; i<6; i++) {
        for (int j=0; j<6; j++) {
            pre[i][j] = 0;
        }
    }
}

void fill(int v, int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = v%10;
        v/=10;
    }

}

void unfill(int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = 0;
    }
}

int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

const int TABLESIZE = 1234567;
int cache[6][6][TABLESIZE];

int getDig(int val) {
    int ct = 0;
    while (val) {
        val /= 10;
        ct++;
    }
    return max(ct, 1);
}

lld getState() {
    unsigned long long ret = 10000007;
    ret = ret<<5 ^ pre[1][0];
    ret = ret<<5 ^ pre[2][0];
    ret = ret<<5 ^ pre[2][1];
    ret = ret<<5 ^ pre[3][0];
    ret = ret<<5 ^ pre[3][1];
    ret = ret<<5 ^ pre[3][2];
    ret = ret<<5 ^ pre[4][0];
    ret = ret<<5 ^ pre[4][1];
    ret = ret<<5 ^ pre[4][2];
    ret = ret<<5 ^ pre[4][3];
    return ret % TABLESIZE;
}

int findlow(int val) {
    if (low[val] == val) {
        return val;
    }
    return low[val] = findlow(low[val]);
}

int ways(int r) {
    if (r == ord) {
        return 1;
    }
    int hashID = getState();
    if (cache[ord][r][hashID]) {
        return cache[ord][r][hashID];
    }
    int ret = 0;
    int prefix = 0;
    for (int i=0; i<r; i++) {
        prefix += pre[r][i] * pow10(ord-i-1);
    }
    int upper = prefix + pow10(ord-r);
    //int *low = lower_bound(p, p+k, prefix);
    int low = ptr[findlow(prefix)]; // can optmise to O(1) with disjoint set
    for (int i = low; i<k && p[i] < upper; i++) {
        fill(p[i], r);
        ret += ways(r+1);
        unfill(r);
    }
    return cache[ord][r][hashID] = ret;
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        fill(pi, 0);
        lld out = ways(1);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;

typedef long long lld;

bool prime[100100];
int k=0;
int p[100100];
int ptr[100100];
int low[100100];

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=0; i<100100; i++) {
        low[i] = i+1;
    }
    low[100099] = 100099;
    ptr[100099] = 100100;
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            low[i] = i;
            ptr[i] = k;
            p[k++] = i;
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    }
}

int ord;
int pre[6][6];

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
    for (int i=0; i<6; i++) {
        for (int j=0; j<6; j++) {
            pre[i][j] = 0;
        }
    }
}

void fill(int v, int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = v%10;
        v/=10;
    }

}

void unfill(int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = 0;
    }
}

int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

const int TABLESIZE = 1234567;
int cache[6][6][TABLESIZE];

int getDig(int val) {
    int ct = 0;
    while (val) {
        val /= 10;
        ct++;
    }
    return max(ct, 1);
}

//hash<int> H;

int getState() {
    lld buff = pre[1][0];
    buff = 10*buff + pre[2][0];
    buff = 10*buff + pre[2][1];
    buff = 10*buff + pre[3][0];
    buff = 10*buff + pre[3][1];
    buff = 10*buff + pre[3][2];
    buff = 10*buff + pre[4][0];
    buff = 10*buff + pre[4][1];
    buff = 10*buff + pre[4][2];
    buff = 10*buff + pre[4][3];
    //lld ret = H(buff);
    //return ret % TABLESIZE;
    return 0;
}

int findlow(int val) {
    if (low[val] == val) {
        return val;
    }
    return low[val] = findlow(low[val]);
}

int ways(int r) {
    if (r == ord) {
        return 1;
    }
    //int hashID = getState();
    //if (cache[ord][r][hashID]) {
    //  return cache[ord][r][hashID];
    //}
    int ret = 0;
    int prefix = 0;
    for (int i=0; i<r; i++) {
        prefix += pre[r][i] * pow10(ord-i-1);
    }
    int upper = prefix + pow10(ord-r);
    int low = ptr[findlow(prefix)];
    for (int i = low; i<k && p[i] < upper; i++) {
        fill(p[i], r);
        ret += ways(r+1);
        unfill(r);
    }
    return ret;
    //return cache[ord][r][hashID] = ret;
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        fill(pi, 0);
        lld out = ways(1);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>
#include <hash_set>

using namespace std;

typedef long long lld;

bool prime[100100];
int k=0;
int p[100100];
int ptr[100100];
int low[100100];

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=0; i<100100; i++) {
        low[i] = i+1;
    }
    low[100099] = 100099;
    ptr[100099] = 100100;
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            low[i] = i;
            ptr[i] = k;
            p[k++] = i;
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    }
}

int ord;
int pre[6][6];

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
    for (int i=0; i<6; i++) {
        for (int j=0; j<6; j++) {
            pre[i][j] = 0;
        }
    }
}

void fill(int v, int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = v%10;
        v/=10;
    }

}

void unfill(int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = 0;
    }
}

int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

const int TABLESIZE = 1234567;
int cache[6][6][TABLESIZE];

int getDig(int val) {
    int ct = 0;
    while (val) {
        val /= 10;
        ct++;
    }
    return max(ct, 1);
}

hash<int> H;

int getState() {
    lld buff = pre[1][0];
    buff = 10*buff + pre[2][0];
    buff = 10*buff + pre[2][1];
    buff = 10*buff + pre[3][0];
    buff = 10*buff + pre[3][1];
    buff = 10*buff + pre[3][2];
    buff = 10*buff + pre[4][0];
    buff = 10*buff + pre[4][1];
    buff = 10*buff + pre[4][2];
    buff = 10*buff + pre[4][3];
    lld ret = H(buff);
    return ret % TABLESIZE;
}

int findlow(int val) {
    if (low[val] == val) {
        return val;
    }
    return low[val] = findlow(low[val]);
}

int ways(int r) {
    if (r == ord) {
        return 1;
    }
    int hashID = getState();
    if (cache[ord][r][hashID]) {
        return cache[ord][r][hashID];
    }
    int ret = 0;
    int prefix = 0;
    for (int i=0; i<r; i++) {
        prefix += pre[r][i] * pow10(ord-i-1);
    }
    int upper = prefix + pow10(ord-r);
    //int *low = lower_bound(p, p+k, prefix);
    int low = ptr[findlow(prefix)]; // can optmise to O(1) with disjoint set
    for (int i = low; i<k && p[i] < upper; i++) {
        fill(p[i], r);
        ret += ways(r+1);
        unfill(r);
    }
    return cache[ord][r][hashID] = ret;
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        fill(pi, 0);
        lld out = ways(1);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;

typedef long long lld;

bool prime[100100];
int k=0;
int p[100100];
int ptr[100100];
int low[100100];

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=0; i<100100; i++) {
        low[i] = i+1;
    }
    low[100099] = 100099;
    ptr[100099] = 100100;
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            low[i] = i;
            ptr[i] = k;
            p[k++] = i;
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    }
}

int ord;
int pre[6][6];

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
    for (int i=0; i<6; i++) {
        for (int j=0; j<6; j++) {
            pre[i][j] = 0;
        }
    }
}

void fill(int v, int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = v%10;
        v/=10;
    }

}

void unfill(int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = 0;
    }
}

int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

const int TABLESIZE = 1234567;
int cache[6][6][TABLESIZE];

int getDig(int val) {
    int ct = 0;
    while (val) {
        val /= 10;
        ct++;
    }
    return max(ct, 1);
}

unsigned long long hashVal(char *arr) {
    unsigned long long ret = 10000007;
    for (int i=0; i<10; i++) {
        ret = ((ret<<5) + ret) + arr[i];
    }
    return ret;
}

int getState() {
    char buff[11];
    buff[0] = pre[1][0];
    buff[1] = pre[2][0];
    buff[2] = pre[2][1];
    buff[3] = pre[3][0];
    buff[4] = pre[3][1];
    buff[5] = pre[3][2];
    buff[6] = pre[4][0];
    buff[7] = pre[4][1];
    buff[8] = pre[4][2];
    buff[9] = pre[4][3];
    unsigned long long ret = hashVal(buff);
    return ret % TABLESIZE;
}

int findlow(int val) {
    if (low[val] == val) {
        return val;
    }
    return low[val] = findlow(low[val]);
}

int ways(int r) {
    if (r == ord) {
        return 1;
    }
    //int hashID = getState();
    //if (cache[ord][r][hashID]) {
    //  return cache[ord][r][hashID];
    //}
    int ret = 0;
    int prefix = 0;
    for (int i=0; i<r; i++) {
        prefix += pre[r][i] * pow10(ord-i-1);
    }
    int upper = prefix + pow10(ord-r);
    int low = ptr[findlow(prefix)];
    for (int i = low; i<k && p[i] < upper; i++) {
        fill(p[i], r);
        ret += ways(r+1);
        unfill(r);
    }
    return ret;
    //return cache[ord][r][hashID] = ret;
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        fill(pi, 0);
        lld out = ways(1);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;

typedef long long lld;

bool prime[100100];
int k=0;
int p[100100];;

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            p[k++] = i;
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    }
}

int ord;
int pre[6][6];

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
    for (int i=0; i<6; i++) {
        for (int j=0; j<6; j++) {
            pre[i][j] = 0;
        }
    }
}

void fill(int v, int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = v%10;
        v/=10;
    }

}

void unfill(int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = 0;
    }
}

int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

map<lld, lld> cache[6][6];

int getDig(int val) {
    int ct = 0;
    while (val) {
        val /= 10;
        ct++;
    }
    return max(ct, 1);
}

lld getState() {
    lld ret = 0;
    ret = pre[1][0];
    ret = ret*10 + pre[2][0];
    ret = ret*10 + pre[2][1];
    ret = ret*10 + pre[3][0];
    ret = ret*10 + pre[3][1];
    ret = ret*10 + pre[3][2];
    ret = ret*10 + pre[4][0];
    ret = ret*10 + pre[4][1];
    ret = ret*10 + pre[4][2];
    ret = ret*10 + pre[4][3];
    return ret;
}

lld ways(int r) {
    if (r == ord) {
        return 1;
    }
    if (cache[ord][r].count(getState())) {
        return cache[ord][r][getState()];
    }
    lld ret = 0;
    int prefix = 0;
    for (int i=0; i<r; i++) {
        prefix += pre[r][i] * pow10(ord-i-1);
    }
    int upper = prefix + pow10(ord-r);
    int *low = lower_bound(p, p+k, prefix);
    for (int i = low-p; i<k && p[i] < upper; i++) {
        fill(p[i], r);
        ret += ways(r+1);
        unfill(r);
    }
    return cache[ord][r][getState()] = ret;
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        fill(pi, 0);
        lld out = ways(1);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;

typedef long long lld;

bool prime[100100];
int k=0;
int p[100100];
int ptr[100100];
int low[100100];

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=0; i<100100; i++) {
        low[i] = i+1;
    }
    low[100099] = 100099;
    ptr[100099] = 100100;
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            low[i] = i;
            ptr[i] = k;
            p[k++] = i;
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    }
}

int ord;
int pre[6][6];

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
    for (int i=0; i<6; i++) {
        for (int j=0; j<6; j++) {
            pre[i][j] = 0;
        }
    }
}

void fill(int v, int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = v%10;
        v/=10;
    }

}

void unfill(int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = 0;
    }
}

int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

const int TABLESIZE = 1234567;
int cache[6][6][TABLESIZE];

int getDig(int val) {
    int ct = 0;
    while (val) {
        val /= 10;
        ct++;
    }
    return max(ct, 1);
}

unsigned long long hashVal(char *arr) {
    unsigned long long ret = 10000007;
    for (int i=0; i<10; i++) {
        ret = ((ret<<12) + (ret<<32)^arr[i]) - ret + arr[i];
    }
    return ret;
}

int getState() {
    char buff[11];
    buff[0] = pre[1][0];
    buff[1] = pre[2][0];
    buff[2] = pre[2][1];
    buff[3] = pre[3][0];
    buff[4] = pre[3][1];
    buff[5] = pre[3][2];
    buff[6] = pre[4][0];
    buff[7] = pre[4][1];
    buff[8] = pre[4][2];
    buff[9] = pre[4][3];
    unsigned long long ret = hashVal(buff);
    return ret % TABLESIZE;
}

int findlow(int val) {
    if (low[val] == val) {
        return val;
    }
    return low[val] = findlow(low[val]);
}

int ways(int r) {
    if (r == ord) {
        return 1;
    }
    int hashID = getState();
    if (cache[ord][r][hashID]) {
        return cache[ord][r][hashID];
    }
    int ret = 0;
    int prefix = 0;
    for (int i=0; i<r; i++) {
        prefix += pre[r][i] * pow10(ord-i-1);
    }
    int upper = prefix + pow10(ord-r);
    int low = ptr[findlow(prefix)];
    for (int i = low; i<k && p[i] < upper; i++) {
        fill(p[i], r);
        ret += ways(r+1);
        unfill(r);
    }
    return cache[ord][r][hashID] = ret;
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        fill(pi, 0);
        lld out = ways(1);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;

typedef long long lld;

bool prime[100100];
int k=0;
int p[100100];
int ptr[100100];
int low[100100];

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=0; i<100100; i++) {
        low[i] = i+1;
    }
    low[100099] = 100099;
    ptr[100099] = 100100;
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            low[i] = i;
            ptr[i] = k;
            p[k++] = i;
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    }
}

int ord;
int use[6];

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
}

int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

int findlow(int val) {
    if (low[val] == val) {
        return val;
    }
    return low[val] = findlow(low[val]);
}

int ways(int r) {
    if (r == ord) {
        return 1;
    }
    int ret = 0;
    int prefix = 0;
    for (int i=0; i<r; i++) {
        prefix = prefix*10 + (use[i]/pow10(ord-r-1))%10;
    }
    prefix*=pow10(ord-r);
    int upper = prefix + pow10(ord-r);
    int low = ptr[findlow(prefix)];
    for (int i = low; i<k && p[i] < upper; i++) {
        use[r] = p[i];
        ret += ways(r+1);
    }
    return ret;
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        use[0] = pi;
        lld out = ways(1);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;

typedef long long lld;

bool prime[100100];
int k=0;
int p[100100];
int ptr[100100];
int low[100100];

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=0; i<100100; i++) {
        low[i] = i+1;
    }
    low[100099] = 100099;
    ptr[100099] = 100100;
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            low[i] = i;
            ptr[i] = k;
            p[k++] = i;
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    }
}

int ord;
int pre[6][6];

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
    for (int i=0; i<6; i++) {
        for (int j=0; j<6; j++) {
            pre[i][j] = 0;
        }
    }
}

void fill(int v, int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = v%10;
        v/=10;
    }

}

void unfill(int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i][r] = 0;
    }
}

int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

const int TABLESIZE = 1234567;
int cache[6][6][TABLESIZE];

int getDig(int val) {
    int ct = 0;
    while (val) {
        val /= 10;
        ct++;
    }
    return max(ct, 1);
}

hash<int> H;

int getState() {
    lld buff = pre[1][0];
    buff = 10*buff + pre[2][0];
    buff = 10*buff + pre[2][1];
    buff = 10*buff + pre[3][0];
    buff = 10*buff + pre[3][1];
    buff = 10*buff + pre[3][2];
    buff = 10*buff + pre[4][0];
    buff = 10*buff + pre[4][1];
    buff = 10*buff + pre[4][2];
    buff = 10*buff + pre[4][3];
    lld ret = H(buff);
    return ret % TABLESIZE;
}

int findlow(int val) {
    if (low[val] == val) {
        return val;
    }
    return low[val] = findlow(low[val]);
}

int ways(int r) {
    if (r == ord) {
        return 1;
    }
    int hashID = getState();
    if (cache[ord][r][hashID]) {
        return cache[ord][r][hashID];
    }
    int ret = 0;
    int prefix = 0;
    for (int i=0; i<r; i++) {
        prefix += pre[r][i] * pow10(ord-i-1);
    }
    int upper = prefix + pow10(ord-r);
    //int *low = lower_bound(p, p+k, prefix);
    int low = ptr[findlow(prefix)]; // can optmise to O(1) with disjoint set
    for (int i = low; i<k && p[i] < upper; i++) {
        fill(p[i], r);
        ret += ways(r+1);
        unfill(r);
    }
    return cache[ord][r][hashID] = ret;
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        fill(pi, 0);
        lld out = ways(1);
        cout << out << endl;
    }
    return 0;
}


#include <cstdio>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>

using namespace std;

typedef long long lld;

bool prime[100100];
int k=0;
int p[100100];;

void calcP() {
    memset(prime, true, sizeof(prime));
    for (int i=2; i<100100; i++) {
        if (prime[i]) {
            p[k++] = i;
            for (int j=2*i; j<100100; j+=i) {
                prime[j] = false;
            }
        }
    }
}

int ord;
int pre[6];

void reset(int v) {
    ord = 0;
    while (v != 0) {
        v/=10;
        ord++;
    }
    for (int i=0; i<6; i++) {
        pre[i] = 0;
    }
}

void fill(int v, int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i] = pre[i]*10 + v%10;
        v/=10;
    }

}

void unfill(int r) {
    for (int i=ord-1; i>r; i--) {
        pre[i] /= 10;
    }
}

int pow10(int ind) {
    int ret = 1;
    for (int i=0; i<ind; i++) {
        ret *= 10;
    }
    return ret;
}

lld ways(int r) {
    if (r == ord) {
        return 1;
    }
    lld ret = 0;
    int prefix = pre[r] * pow10(ord-r);
    int upper = (pre[r]+1) * pow10(ord-r);
    int *low = lower_bound(p, p+k, prefix);
    for (int i = low-p; i<k && p[i] < upper; i++) {
        fill(p[i], r);
        ret += ways(r+1);
        unfill(r);
    }
    return ret;
}

int main() {
    calcP();
    int N;
    scanf("%d", &N);
    for (int i=0; i<N; i++) {
        int pi;
        scanf("%d", &pi);
        reset(pi);
        fill(pi, 0);
        lld out = ways(1);
        cout << out << endl;
    }
    return 0;
}