#include<iostream>
#include<list>
#include<queue>
using namespace std;
#define LL long long
struct Edge
{
	LL v;
	LL u;
	LL s;
	bool vis;//false 没被访问过
}edge[100005];

struct Node
{
	LL num;
	bool x;//true为正，false为负；
	list<LL> L;
}node[200005];

bool vis[200005];

LL tol;

LL low = 0;
LL up = 0xfffffffffffffff;

queue<LL> q;

LL jie;

bool f()
{
	while (!q.empty())
	{
		LL top = q.front();
		q.pop();
		list<LL>::iterator it;
		for (it = node[top].L.begin(); it != node[top].L.end(); it++)
		{
			if (!(edge[*it].vis))
			{
				LL u = edge[*it].u;
				LL v = edge[*it].v;
				if (vis[u] && vis[v])
				{
					if (node[u].x^node[v].x)
					{
						if (node[u].num + node[v].num != edge[*it].s)
						{
							return false;
						}
					}
					else if(node[u].x)
					{
						LL temp = -(node[u].num + node[v].num - edge[*it].s);
						if (temp <= 0)
						{
							return false;
						}

						if (temp & 1)
						{
							return false;
						}
						else
						{
							temp /= 2;
							if (!jie)
							{
								jie = temp;
							}
							else if(temp!=jie)
							{
								return false;
							}
						}
					}
					else
					{
						LL temp = (node[u].num + node[v].num - edge[*it].s);
						if (temp <= 0)
						{
							return false;
						}
						if (temp & 1)
						{
							return false;
						}
						else
						{
							temp /= 2;
							if (!jie)
							{
								jie = temp;
							}
							else if (temp != jie)
							{
								return false;
							}
						}
					}
				}
				else if(vis[u])
				{
					node[v].x = !node[u].x;
					node[v].num = edge[*it].s - node[u].num;
					if (node[v].x)
					{
						if (low < -node[v].num)
						{
							low = -node[v].num;
						}
					}
					else
					{
						if (up > node[v].num)
						{
							up = node[v].num;
						}
					}
					vis[v] = true;
					q.push(v);
				}
				else
				{
					node[u].x = !node[v].x;
					node[u].num = edge[*it].s - node[v].num;
					if (node[u].x)
					{
						if (low < -node[u].num)
						{
							low = -node[u].num;
						}
					}
					else
					{
						if (up > node[u].num)
						{
							up = node[u].num;
						}
					}
					vis[u] = true;
					q.push(u);
				}

				edge[*it].vis = true;
			}
		}


	}
	return true;
}
LL ans = 1;
int main()
{
	LL N, M;
	cin >> N >> M;
	for (LL i = 1; i <= N; i++)
	{
		LL t1, t2, t3;
		cin >> t1 >> t2 >> t3;
		edge[tol].s = t3;
		edge[tol].u = t1;
		edge[tol].v = t2;
		node[t1].L.push_back(tol);
		node[t2].L.push_back(tol);
		tol++;
	}

	for (LL i = 1; i <= N; i++)
	{
		if (!vis[i])
		{
			q.push(i);
			node[i].num = 0;
			node[i].x = true;
			vis[i] = true;
			jie = 0;
			if (!f())
			{
				cout << "0" << endl;
				return 0;
			}
			else
			{
				if(!jie)
					ans *= (up - low - 1);
			}
		}
	}
	cout << ans << endl;
	
	return 0;
}