#include<bits/stdc++.h> usingnamespace std; longlongmodpow(longlong x, longlong y, longlong M){ longlong ans = 1; while (y > 0){ if (y % 2 == 1){ ans *= x; ans %= M; } x *= x; x %= M; y /= 2; } return ans; } structunionfind{ vector<int> p; unionfind(int N){ p = vector<int>(N, -1); } introot(int x){ if (p[x] < 0){ return x; } else { p[x] = root(p[x]); return p[x]; } } boolsame(int x, int y){ returnroot(x) == root(y); } voidunite(int x, int y){ x = root(x); y = root(y); if (x != y){ if (p[x] < p[y]){ swap(x, y); } p[y] += p[x]; p[x] = y; } } }; intmain(){ int N, M; cin >> N >> M; vector<int> A(N); for (int i = 0; i < N; i++){ cin >> A[i]; } vector<tuple<int, int, int>> E; for (int i = 0; i < N; i++){ for (int j = i + 1; j < N; j++){ E.push_back(make_tuple((modpow(A[i], A[j], M) + modpow(A[j], A[i], M)) % M, i, j)); } } sort(E.begin(), E.end(), greater<tuple<int, int, int>>()); unionfind UF(N); longlong ans = 0; for (int i = 0; i < N * (N - 1) / 2; i++){ int c = get<0>(E[i]); int u = get<1>(E[i]); int v = get<2>(E[i]); if (!UF.same(u, v)){ UF.unite(u, v); ans += c; } } cout << ans << endl; }