#include <stdio.h>
#include <stdlib.h>

#define TRY_MAX 4000000L

int main( int argc, char **argv ) {
    char flag[TRY_MAX];
    int count;

    long int start=1;
    long int inc=1;
    long long int i, k, n, r1, r2, r3, r4;

    for( i = 0; i < TRY_MAX; i++ ) flag[i] = 1;

    if( flag == NULL ) {
	fprintf( stderr, "Couldn't allocate flag[] array.\n" );
	return 1;
    }

    /* if increment is given use it */
    if( argc > 2 ) {
        fprintf( stderr, "arg2: %s\n" , argv[2] );
	inc = strtol( argv[2], NULL, 10 );
    }

    /* if start is given use it */
    if( argc > 1 ) {
        fprintf( stderr, "arg1: %s\n" , argv[1] );
	start = strtol( argv[1], NULL, 10 );
    }

    fprintf( stderr, "start: %ld  inc: %ld\n", start, inc );


    for( n = start; n < TRY_MAX; n += inc ) {
	/* We'll count down when we mark off different hits */
	count = n;
	/* fprintf( stderr, "%lld,\r", n ); */

	/* Reset all of the hits to zero */
	for( i = 0; i < n; i++ ) flag[i]=1;

	for( k = 0; k < n; k++ ) {
	    /* calculate the 4 polynomials */
	    r1 = ( 3*k*k ) % n;
	    r2 = ( 3*k+2 )*k % n;
	    r3 = (( 3*k+3 )*k + 1 ) % n;
	    r4 = (( 3*k+5 )*k + 2 ) % n;

	    /* one sanity check, just to make sure */
	    if( r1 < 0 ) {
		fprintf( stderr, "r1 is negative\n" );
		exit( 1 );
	    }

	    /* check each result agains our list */
	    if( flag[r1] ) {
		flag[r1] = 0;
		count--;
	    }

	    if( flag[r2] ) {
		flag[r2] = 0;
		count--;
	    }

	    if( flag[r3] ) {
		flag[r3] = 0;
		count--;
	    }

	    if( flag[r4] ) {
		flag[r4] = 0;
		count--;
	    }
	}

	if( !count ) {
	    fprintf( stdout, "%lld\n", n );
	    fflush( stdout );
	}
    }

    exit( 0 );
}