#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read()
{
int x=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
while (ch>='0'&&ch<='9'){x=x*10+ch-48;ch=getchar();}
return x*f;
}
int n=read(),s1=read(),s2=read(),s3=read(),s4=read(),a[5000005],mod,ans,maxi=-1e18;
int f(int x){
int k=s1*x;
k%=mod;
k*=x;
k%=mod;
k*=x;
k%=mod;
int l=s2*x;
l%=mod;
l*=x;
l%=mod;
k+=l;
k%=mod;
k+=s3*x;
k%=mod;
k+=s4;
k%=mod;
return k;
}
signed main(){
a[1]=read();
mod=read();
for(int i=2; i<=n; i++){
a[i]=(f(a[i-1])+f(a[i-2]))%mod;
ans=max(ans,maxi-a[i]),maxi=max(maxi,a[i]);
}
cout<<(ans+1)/2;
return 0;
}