#include <bits/stdc++.h>
using namespace std;

struct UnionFind {
    vector<int> par;
    vector<int> sz;
    int64_t ans = 0;
    int cnt = 0;

    UnionFind(int n=0){
        if(n>0) initialize(n);
    }

    void initialize(int n){
        par.resize(n);
        sz.resize(n);
        for(int i=0; i<n; i++){
            par[i] = i;
            sz[i] = 1;
        }
    }

    int find(int x){
        if(par[x] == x){
            return x;
        }else{
            return par[x] = find(par[x]);
        }
    }

    void unite(int x, int y, int c){
        x = find(x);
        y = find(y);
        if(x == y) return;
        if(sz[x] > sz[y]) swap(x, y);
        par[x] = y;
        sz[y] += sz[x];
        cnt++;
        ans += c;
    }

    bool same(int x, int y){
        return find(x) == find(y);
    }

    int size(int x){
        return sz[find(x)];
    }
};

int main(){
    int N, Q;
    cin >> N >> Q;
    map<int, vector<pair<int, int>>> qs;
    for(int i=0; i<Q; i++){
        int a, b, c;
        cin >> a >> b >> c;
        qs[c].emplace_back(a, b);
    }
    int mn = qs.begin()->first;

    UnionFind uf(N);
    vector<int> st[2];
    bool used[200000][2] = {0};
    for(int c=mn; uf.cnt < N-1;  c++){
        vector<int> nxt;
        for(int a : st[c%2]) if(!used[a][c%2]){
            used[a][c%2] = true;
            int b = (a+1) % N;
            uf.unite(a, b, c);
            nxt.push_back(b);
        }
        st[c%2] = nxt;
        if(qs.count(c)) for(auto& p : qs[c]){
            int a = p.first, b = p.second;
            uf.unite(a, b, c);
            st[c%2].push_back(b);
            st[(c+1)%2].push_back(a);
        }
    }
    cout << uf.ans << endl;
    return 0;
}
