If we choose to use periodic boundary conditions we can code the above expression as
jm=N;
for ( j=1; j <=N ; j++) {
energy += spin[j]*spin[jm];
jm = j ;
}
The magnetization is however the same, defined as Mi=N∑j=1sj, where we sum over all spins for a given configuration i.