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

typedef long long ll;
const int maxn = 100005;

inline int gi()
{
	char c = getchar();
	while (c < '0' || c > '9') c = getchar();
	int sum = 0;
	while ('0' <= c && c <= '9') sum = sum * 10 + c - 48, c = getchar();
	return sum;
}

int n, m;
struct edge
{
	int to, next, w;
} e[maxn * 2];
int h[maxn], tot, ecnt, scnt, label;
int vis[maxn], f[3];

inline void add(int u, int v)
{
	e[++tot] = (edge) {v, h[u], 1}; h[u] = tot;
	e[++tot] = (edge) {u, h[v], 2}; h[v] = tot;
}

void dfs(int u, int d)
{
	vis[u] = d; f[d] += 1; ++scnt;
	for (int i = h[u], v; v = e[i].to, i; i = e[i].next) {
		if (e[i].w == 1) ++ecnt;
		if (vis[v] == -1) dfs(v, (d + e[i].w) % 3);
		else if (vis[v] != (vis[u] + e[i].w) % 3) label = 0;
	}
}

int main()
{
	n = gi(); m = gi();
	for (int u, v, i = 1; i <= m; ++i) {
		u = gi(); v = gi();
		add(u, v);
	}

	memset(vis, -1, sizeof(vis));
	ll ans = 0;
	for (int i = 1; i <= n; ++i) {
		if (vis[i] == -1) {
			label = 1; f[0] = f[1] = f[2] = 0; scnt = ecnt = 0; dfs(i, 0);
			if (label) {
				if (!min(f[0], min(f[1], f[2]))) ans += ecnt;
				else ans += (ll)f[0] * f[1] + (ll)f[1] * f[2] + (ll)f[2] * f[0];
			} else ans += (ll)scnt * scnt;
		}
	}

	printf("%lld\n", ans);
	
	return 0;
}
