#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define forE(i,x)  for(int i=head[x];i!=-1;i=ne[i])
using namespace std;
inline void read(int &x){
	x=0;char ch=getchar();int f=1;
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=10*x+ch-'0';ch=getchar();}x*=f;
}
inline void judge(){
	freopen("table.in","r",stdin);
	freopen("table.out","w",stdout);
}
const int maxn=100005;
typedef long long i64;
int num,n,m,head[maxn],t[maxn<<1],ne[maxn<<1],v[maxn<<1];
inline void addedge(int x,int y,int z){
	ne[++num]=head[x];head[x]=num;t[num]=y;v[num]=z;
}
bool vis[maxn];
int cnt[4],d[maxn],T;
bool godie=0;
inline void dfs(int x,int l){
	vis[x]=1;d[x]=l;cnt[l]++;
	forE(i,x)if(!vis[t[i]]){
		dfs(t[i],(l+v[i])%3);T++;
	}else{
		if((l+v[i])%3!=d[t[i]])godie=1;T++;
	}
}i64 ans=0;
int main(){
	read(n);read(m);
	rep(i,1,n)head[i]=-1;
	rep(i,1,m){
		int x,y;read(x);read(y);
		addedge(x,y,1);
		addedge(y,x,2);
	}
	rep(i,1,n){
		if(vis[i])continue;memset(cnt,0,sizeof(cnt));godie=0;T=0;
		dfs(i,0);i64 sum=cnt[0]+cnt[1]+cnt[2];
		if(godie){
			ans+=sum*sum;continue;	
		}else{
			if(cnt[0]&&cnt[1]&&cnt[2]){
				ans+=1ll*cnt[0]*cnt[1]+1ll*cnt[0]*cnt[2]+1ll*cnt[1]*cnt[2];
			}else{
				ans+=T/2;
			}
		}
	}cout<<ans<<endl;
}