type t = FIN | ANS of int | ILL;;

Scanf.scanf "%d %d" (fun n m ->
    let nei = Array.make n [] in
    for i = 1 to m do
        Scanf.scanf " %d %d %d" (fun u v s ->
            let u = u - 1 in
            let v = v - 1 in
            nei.(u) <- (v, s) :: nei.(u);
            nei.(v) <- (u, s) :: nei.(v);
        )
    done;

    let dist = Array.make n (0, 0) in

    let rec loop cur =
        let (c, v) = dist.(cur) in
        let rec loop2 = function
            | [] -> FIN
            | (nn, nc) :: tl ->
                let mc, mv = nc - c, -v in
                if dist.(nn) = (0, 0) then (
                    dist.(nn) <- mc, mv;
                    let ret = loop nn in
                    if ret = FIN then loop2 tl else ret)
                else (
                    if dist.(nn) = (mc, mv) then loop2 tl else (
                        let qc, qv = dist.(nn) in
                        if mv = qv then ILL else
                        if (qc - mc) mod (mv - qv) = 0 &&
                            (qc - mc) / (mv - qv) > 0 then (
                                ANS ((qc - mc) / (mv - qv))
                            ) else ILL
                    )
                )
        in
        loop2 nei.(cur)
    in

    let single k =
        let dist2 = Array.make n 0 in
        let rec loop cur =
            let c = dist2.(cur) in
            let rec loop2 = function
                | [] -> 1
                | (nn, nc) :: tl ->
                        let mc = nc - c in
                        if mc <= 0 then 0 else (
                            if dist2.(nn) = 0 then (
                                dist2.(nn) <- mc;
                                if loop nn = 1 then loop2 tl else 0
                            ) else (
                                if dist2.(nn) = mc then loop2 tl else 0
                            )
                        )
            in
            loop2 nei.(cur)
        in
        dist2.(0) <- k;
        loop 0
    in
    let check dist =
        let rec loop i l r =
            if i = n then max 0 (r - l + 1) else
                let (c, v) = dist.(i) in 
                if v = 1 then loop (i + 1) (max l (-c)) r
                         else loop (i + 1) l (min r (c - 1))
        in
        loop 0 1 max_int
    in

    dist.(0) <- 0, 1;
    match loop 0 with
    | FIN   -> Printf.printf "%d\n" @@ check dist
    | ANS k -> Printf.printf "%d\n" @@ single k
    | ILL   -> Printf.printf "0\n"
)