#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
const long long INF = 1LL << 60;    // 1.15x10^18
using edge = pair<int, long long>;
using Graph = vector<vector<edge>>;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }

Graph g;
vector<long long> a, b;
long long x = INF;
bool dfs(int u) {
    bool ret = true;
    for (auto &p: g[u]) {
        int v = p.first; long long s = p.second;
        if (a[v] == INF) {
            a[v] = -a[u];
            b[v] = s - b[u];
            ret &= dfs(v);
        } else {
            if (x == INF) {
                long long num = s - b[u] - b[v];
                long long den = a[u] + a[v];
                if (den == 0) {
                    if (num == 0) {  }
                    else return false;
                } else {
                    if (num % den != 0) return false;
                    x = num / den;
                }
            } else {
                if (a[u] * x + b[u] + a[v] * x + b[v] != s) return false;
            }
        }
    }
    return ret;
}

int main() {
    int n, m; cin >> n >> m;
    g.resize(n);
    while (m--) {
        int u, v, s; cin >> u >> v >> s; u--, v--;
        g[u].emplace_back(v, s);
        g[v].emplace_back(u, s);
    }
    a.assign(n, INF);
    b.assign(n, INF);
    a[0] = 1, b[0] = 0;
    if (!dfs(0)) return !(cout << 0 << endl);
    if (x != INF) {
        for (int i = 0; i < n; i++) {
            if (a[i] * x + b[i] <= 0) return !(cout << 0 << endl);
        }
        cout << 1 << endl;
    } else {
        long long l = -INF, r = INF;
        for (int i = 0; i < n; i++) {
            if (a[i] > 0) {
                chmax(l, (1 - b[i] + a[i] - 1) / a[i]);
            } else if (a[i] < 0) {
                chmin(r, (1 - b[i]) / a[i]);
            }
        }
        cout << max(0LL, r - l + 1) << endl;
    }
    return 0;
}