#include <algorithm>
#include <cstring>
#include <cctype>
#include <cstdio>
using namespace std;
typedef long long int64;
inline int read(int f = 1, int x = 0, char ch = ' ')
{
    while(!isdigit(ch = getchar())) if(ch == '-') f = -1;
    while(isdigit(ch)) x = x*10+ch-'0', ch = getchar();
    return f*x;
}
const int N = 1e5+5;
struct Edge
{
    int next, to, w;
    Edge(int next = 0, int to = 0, int w = 0):next(next), to(to), w(w) {};
}edge[N<<1];
int tot, head[N];
void add(int x, int y, int z) { edge[++tot] = Edge(head[x], y, z); head[x] = tot; }
int n, m, c[N];
int64 ans, f[3], s;
bool color(int x, int col)
{   
    if(c[x]) return c[x] == col+1;   
    c[x] = col+1, ++f[col];
    bool ret = true;
    for(int i = head[x]; i; i = edge[i].next)
    {
        int y = edge[i].to, z = edge[i].w; s += z == 1;
        if(!color(y, col+z >= 3?col+z-3:col+z)) ret = false;
    }
    return ret;
}
int main()
{
    n = read(), m = read();
    for(int i = 1; i <= m; ++i)
    {
        int x = read(), y = read();
        add(x, y, 1), add(y, x, 2);
    }
    for(int x = 1; x <= n; ++x)
        if(!c[x])
        {
            s = f[0] = f[1] = f[2] = 0;
            if(!color(x, 1)) s = f[0]+f[1]+f[2], ans += s*s;
            else if(f[0]&&f[1]&&f[2]) ans += f[0]*f[1]+f[1]*f[2]+f[0]*f[2];
            else ans += s;
        }
    printf("%lld\n", ans);
    return 0;
}