#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <utility>
using namespace std;
typedef long long ll;

int par[200010],sz[200010];
void init(int n){
	for(int i=0;i<n;i++){
		par[i] = i; sz[i] = 1;
	}
}

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

void unite(ll x, ll y){
	x = find(x); y = find(y);
	if(x==y) return;
	if(sz[x]<sz[y]) swap(x,y);
	par[y] = x; sz[x] += sz[y];
}

bool same(ll x, ll y){
	return find(x)==find(y);
}
typedef pair<ll,pair<ll,ll>> P;
priority_queue<P,vector<P>,greater<P>> que;
int main(){
	int i,n,q;
	cin >> n >> q;
	init(n);
	for(i=0;i<q;i++){
		ll a,b,c; cin >> a >> b >> c;
		que.push({c,{a,b}});
		que.push({c + 1,{(a + 1)%n,b}});
	}
	ll res = 0;
	while(que.size()){
		P p = que.top();
		que.pop();
		ll u = p.second.first,v = p.second.second;
		if(same(u,v)) continue;
		unite(u,v); res += p.first;
		p.first += 2; (p.second.first += 1) %= n; (p.second.second += 1) %= n;
		que.push(p);
	}
	cout << res << endl;
}
	