Search code examples
cloopselliptic-curvefinite-field

in C ,why result is different after only changing loop boundary?


I met this problem when verifying whether points in a finite field GF(13) is on elliptic curve y^2 = x^3 + x + 1: first I set the loop boundary as i<2,the results came out right.

#include <stdio.h>
#include <math.h>

void main ()
{
    int a[13], b[13];
    int j, i, m, k = 0;
    for (i = 0; i < 2; i++)
        for (j = 0; j < 13; j++)
            if ((i * i * i + i + 1) % 13 == (j * j) % 13) {
                a[k] = i;
                b[k] = j;
                k++;
            }
    printf ("\n There are %d points on the curve\nThe points are: ", k);
    for (m = 0; m < k; m++)
        printf ("\nx=%d,y=%d \n", a[m], b[m]);
}

The result is link 1

after I change the i<2 to i<13,

for(i=0;i<13;i++)

the first 4 points changed: link 2


Solution

  • You are entering undefined behavior. If you set a break inside the loop you will notice that k >= 13 which is outside the bounds of your arrays.

    You could add some bounds checking and consider the size of your arrays.