import sys input = sys.stdin.readline from heapq import heappop,heappush from math import gcd N,M,K=list(map(int,input().split())) E=[[] for i in range(N)] for i in range(M): x,y,t=list(map(int,input().split())) x-=1 y-=1 E[x].append((y,t)) E[y].append((x,t)) DIS=[1<<63]*N DIS[0]=0 Q=[(0,0)] while Q: time,ind=heappop(Q) if DIS[ind]!=time: continue for to,cost in E[ind]: if DIS[to]>DIS[ind]+cost: DIS[to]=DIS[ind]+cost heappush(Q,(DIS[to],to)) DIS2=[1<<63]*N DIS2[N-1]=0 Q=[(0,N-1)] while Q: time,ind=heappop(Q) if DIS2[ind]!=time: continue for to,cost in E[ind]: if DIS2[to]>DIS2[ind]+cost: DIS2[to]=DIS2[ind]+cost heappush(Q,(DIS2[to],to)) ANS=K L=[] for i in range(N): ANS=gcd(ANS,DIS[i]+DIS2[i]) #print(DIS[i]+DIS2[i]) L.append((DIS[i]+DIS2[i])%K) L=sorted(set(L)) #print("!",ANS) for i in range(N): for _,t in E[i]: ANS=gcd(ANS,2*t) for x in L: y=K-x if y%(2*t)==0: print(0) exit() print(ANS)