Example #1
0
File: 03.c Project: mBlack95/12
int main() {
	int x, y;
	printf("Vavedete x: ");
	scanf("%d", &x);
	printf("Vavedete y: ");
	scanf("%d", &y);
    while (x >= y) {
	printf("Vavedete y: ");
	scanf("%d", &y);
	}

	int result, z, n=0;
	for( x; x<=y; x++) {
		result = check_prime(x);
		if (result == 1) {
			z=3+10*n;
			result = check_prime(z);
			if (result == 1) {
				if (x == z) printf("%d ", x), n++;
			}
			else n++;		
		}
	};
	printf("\n");
}
Example #2
0
int main(){
	int (*algo)(int);

	printf("Start! Check prime_num algo time %ld \n", CLOCKS_PER_SEC);
	algo = prime1;
	check_prime("prime1", algo);

	algo = prime2;
	check_prime("prime2", algo);
	return 0;
}
Example #3
0
// Checks that (p,g) is acceptable pair for DH
int tglmp_check_DH_params (struct tgl_state *TLS, TGLC_bn *p, int g) {
  if (g < 2 || g > 7) { return -1; }
  if (TGLC_bn_num_bits (p) != 2048) { return -1; }
  
  TGLC_bn *t = TGLC_bn_new ();
  
  TGLC_bn *dh_g = TGLC_bn_new ();
  
  ensure (TGLC_bn_set_word (dh_g, 4 * g));
  ensure (TGLC_bn_mod (t, p, dh_g, TLS->TGLC_bn_ctx));
  int x = TGLC_bn_get_word (t);
  assert (x >= 0 && x < 4 * g);

  TGLC_bn_free (dh_g);

  int res = 0;
  switch (g) {
  case 2:
    if (x != 7) { res = -1; }
    break;
  case 3:
    if (x % 3 != 2) { res = -1; }
    break;
  case 4:
    break;
  case 5:
    if (x % 5 != 1 && x % 5 != 4) { res = -1; }
    break;
  case 6:
    if (x != 19 && x != 23) { res = -1; }
    break;
  case 7:
    if (x % 7 != 3 && x % 7 != 5 && x % 7 != 6) { res = -1; }
    break;
  }

  if (res < 0 || !check_prime (TLS, p)) { 
    TGLC_bn_free (t);
    return -1; 
  }

  TGLC_bn *b = TGLC_bn_new ();
  ensure (TGLC_bn_set_word (b, 2));
  ensure (TGLC_bn_div (t, 0, p, b, TLS->TGLC_bn_ctx));
  if (!check_prime (TLS, t)) { 
    res = -1;
  }
  TGLC_bn_free (b);
  TGLC_bn_free (t);
  return res;
}
Example #4
0
File: main.cpp Project: NFA/euler
bool is_prime(int number) {
  static std::vector<int> prime_vector{2};
  static euler::prime_generator<int> primes;

  if (prime_vector.back() > number) {
    return check_prime(prime_vector, number);
  }
  int newp = 0;
  while (prime_vector.back() < number) {
    prime_vector.push_back(*primes);
    ++primes;
    ++newp;
  }
  return check_prime(prime_vector, number);
}
Example #5
0
int main(void)
{
	int num[128];
	int N = 100;
	int i, j, ret;

	for (i = 1; i <= N; i++)
		num[i] = 1;

	num[1] = 0;
	for (i = 2; i <= N; i++) {
		if (!num[i])
			continue;
		ret = check_prime(i);
		if (!ret) {
			num[i] = 0;
			continue;
		}

		for (j = 2; i * j <= N; j++) {
			//printf("main: put num[%d] to 0\n", i * j);
			num[i * j] = 0;
		}
	}

	for (i = 1; i <= N; i++)
		if (num[i])
			printf("%d ", i);
	printf("\n");


	return 0;
}
Example #6
0
int main()
{
    int n, prime_number = 1;
    int result;
    unsigned long long number = 100ULL;
    unsigned long long product = 1;

    printf("\n 1 : 2");

    for(n=3; n<=number; n++)
    {
        result = check_prime(n);

        if ( result == 1 )
        {
            prime_number++;
            product *= n;
            printf("\n %d : %d : %llu", prime_number, n, product);


            if(prime_number == 10001)
                break;
        }
    }
    return 0;
}
Example #7
0
hash_t hash_create(hash_freefunc_t free_func, size_t size)
{
	hash_t ht = NULL;

	/* Check passed size */
	if (!check_prime(size)) {
		return NULL;
	}

	ht = (struct hash_object *)malloc(sizeof(*ht));
	if (ht) {
		ht->size = size;
		ht->hash_table = (struct hash_element *)calloc(ht->size,
				sizeof(*ht->hash_table));
		if (ht->hash_table) {
			int i = 0;

			ht->last = NULL;
			ht->count = 0;
			ht->free = free_func;
			for (i = 0; i < ht->size; i++) {
				ht->hash_table[i].key = HASH_KEY_INVALID;
			}
		} else {
			free(ht);
			ht = NULL;
		}
	}

	return ht;
}
unsigned long largest_prime_factor(const unsigned long n) // O(n), runs sqrt(n) times and each can have sqrt(n) for check_prime
{
  unsigned long largest_factor = 0;
  for (unsigned long i = 1; i < n && i*i <= n; i++) {
    if (n % i == 0 && check_prime(i)) largest_factor = i;
  }
  return largest_factor;
}
Example #9
0
int check_primes(int a, int b) {
  int n;
  int s = 0;
  for (n = a; n < b; n++) {
    s += check_prime(n);
  }
  return s;
}
Example #10
0
void work(int x,int n){
	int i;
	if (check_prime(x) == FALSE) return;
	if (n == N) ans[++ans[0]] = x;
	for (i = 0; i <= 4; i++){
		work(x * 10 + num[i],n+1);
	}
	return;
}
Example #11
0
/*
 *
 * is_prime_time - will return the status of primetime
 *
 * returns true if prime time false if non_prime
 *
 * NOTE: Holidays are considered non-prime
 *
 */
enum prime_time
is_prime_time(void)
  {
  /* last_day is used to hold the day during the previous cycle.  It is used so
   * holidays only need to be checked once a day instead of every cycle
   */
  static int last_day = -1;
  enum prime_time ret = PRIME;  /* return code */

  struct tm  *tmptr;   /* current time in a struct tm */

  tmptr = localtime(&(cstat.current_time));

  /* check for holiday: Holiday == non_prime */

  if (conf.holiday_year != 0)  /* year == 0: no prime-time */
    {
    if (tmptr -> tm_year > conf.holiday_year)
      sched_log(PBSEVENT_ADMIN, PBS_EVENTCLASS_FILE, "", "The holday file is out of date, please update it.");
    else if (tmptr -> tm_yday > last_day)
      {
      last_day = tmptr -> tm_yday;
      /* tm_yday starts at 0, and julien date starts at 1 */

      if (is_holiday(tmptr -> tm_yday + 1))
        ret = NON_PRIME;
      }

    /* if ret still equals PRIME then it is not a holidy, we need to check
     * and see if we are in non-prime or prime
     */
    if (ret == PRIME)
      {
      if (tmptr -> tm_wday == 0)
        ret = check_prime(SUNDAY, tmptr);
      else if (tmptr -> tm_wday == 6)
        ret = check_prime(SATURDAY, tmptr);
      else
        ret = check_prime(WEEKDAY, tmptr);
      }
    }

  return ret;
  }
Example #12
0
int
main(int argc, char **argv)
{
    ENGINE *engine = NULL;
    int idx = 0;

    setprogname(argv[0]);

    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &idx))
	usage(1);

    if (help_flag)
	usage(0);

    if(version_flag){
	print_version(NULL);
	exit(0);
    }

    argc -= idx;
    argv += idx;

    OpenSSL_add_all_algorithms();
#ifdef OPENSSL
    ENGINE_load_openssl();
#endif
    ENGINE_load_builtin_engines();

    if (id_string) {
	engine = ENGINE_by_id(id_string);
	if (engine == NULL)
	    engine = ENGINE_by_dso(id_string, id_string);
    } else {
	engine = ENGINE_by_id("builtin");
    }
    if (engine == NULL)
	errx(1, "ENGINE_by_dso failed");

    printf("dh %s\n", ENGINE_get_DH(engine)->name);

    {
	struct prime *p = primes;

	for (; p->name; ++p)
	    if (check_prime(engine, p))
		printf("%s: shared secret OK\n", p->name);
	    else
		printf("%s: shared secret FAILURE\n", p->name);

	return 0;
    }

    return 0;
}
Example #13
0
int main (void){
	const long num = 600851475143;
	long counter=num/2+1;

	while(--counter>0){
	    if(num%counter==0 && check_prime(counter)==1)
	        break;
	}

	printf("%ld\n",counter);
	return 0;
}
Example #14
0
/* Check wether the number X is prime.  */
gcry_error_t
gcry_prime_check (gcry_mpi_t x, unsigned int flags)
{
  gcry_err_code_t err = GPG_ERR_NO_ERROR;
  gcry_mpi_t val_2 = mpi_alloc_set_ui (2); /* Used by the Fermat test. */

  if (! check_prime (x, val_2, NULL, NULL))
    err = GPG_ERR_NO_PRIME;

  mpi_free (val_2);

  return gcry_error (err);
}
int main()
{
    int i,n,result;
    int p,num1,num2,num;
    while(scanf("%d", &n)==1)
    {
        result = check_prime(n);
        if(n==1)
        {
            printf("%d is prime.\n", n);
        }
        else if(result==1)
        {
            num1 = n;
            num2=0;
            while(num1!=0)
            {
                p = num1%10;
                num2 = p + num2*10;
                num1 = num1/10;
            }
            num = check_prime(num2);
            if(num==1 && num2!=n)
            {
                printf("%d is emirp.\n", n);
            }
            else
            {
                printf("%d is prime.\n", n);
            }
        }
        else
        {
            printf("%d is not prime.\n", n);
        }
    }
    return 0;
}
Example #16
0
main()
{
	int n, result;

	printf("Enter an integer to check whether it is prime or not.\n");
	scanf("%d", &n);

	result = check_prime(n);

	if ( result == 1 )
		printf("%d is prime\n", n);
	else
		printf("%d is not prime\n", n);
	return 0;
}
Example #17
0
int main()
{
	int i = 111;

	init_tens();

	while (1) {
		if (check_prime(i))
			break;
		i += 2;
	}

	printf("Result: %d\n", i);

	return 0;
}
Example #18
0
int main(){

  int n1,n2,i,flag;
  
  printf("Enter two numbers(intervals): ");
   scanf("%d %d",&n1, &n2);
  
  printf("Prime numbers between %d and %d are: ", n1, n2);
   for(i=n1+1;i<n2;++i)
   {
      flag=check_prime(i);
      if(flag==0)
         printf("%d ",i);
   }
   return 0;
}
int main(int argc, char const *argv[])
{   
    int number=0;
    scanf("%d",&number);

    while(number<=1003001)
    {
        if (check_palindrome(number) && check_prime(number))
        {
            printf("%d\n",number);
            break;
        }
        number++;
    }  
    return 0;
}
Example #20
0
int main() {
	int N;

	printf("Find all prime numbers between 3 and ?\n");
	scanf("%d", &upper_bound);

	is_prime[2] = 1;

	for (N = 3; N <= upper_bound; N += 2) {
		check_prime(N);
		if (is_prime[N])
			printf("%d is a prime\n",N);
	}

	return 0;
}
Example #21
0
int main()
{
	unsigned long long int i, c = 0, sum = 0;
	
	for(i = 1; i <= 2000000LL; i++)
	{	
		if(check_prime(i))
		{
			c += 1;
			sum += i;
		}
	}
	
	printf("\nSum = %llu, count = %llu, i = %llu", sum, c, i);
	return 0;
}
int main()
{
    int i,n,primes[32000],cnt;
    find_prime(primes,32000);
    while(1)
    {
        scanf("%d",&n);
        if(n==0)
            break;
        cnt=0;
        for(i=3;i<=n/2;i+=2)
        {
            if(primes[i]==1&&check_prime(primes,n-i))
                cnt++;
        }
        printf("%d\n",cnt);
    }
    return 0;
}
Example #23
0
int main()
{int i,sum=2,y=0;
prime *head,*p,*q;
head=NULL;

for(i=3;i<20;i=i+2)
{//p=create_prime(i);
if(head=NULL)
	{ q=create_prime(i);
	 head=q;}
else { y=check_prime(head,i);
	if(y==1)
	{sum+=i;
	q=create_prime(i);
	p=head;
	while(p->next==NULL)
		p=p->next;
	p->next=q;}}}
printf("sum=%d\n",sum);
print_list(head);
}
Example #24
0
void partition_prime(int * arr, int index, int n)
{
  int test;
  int track = 0;

  if (n == 0)
    {
      printf("= ");
      printpartition(arr, index);
      return;
    }
  else
    {
      for (test = 1; test <= n; test++)
	{
	  track = check_prime(test);
	  if ((track <= 2) && (test != 1))
	    {
	      arr[index] = test;
	      partition_prime(arr, index + 1, n - test);
	    }
	}
    }
}
Example #25
0
/****************
 * We do not need to use the strongest RNG because we gain no extra
 * security from it - The prime number is public and we could also
 * offer the factors for those who are willing to check that it is
 * indeed a strong prime.  With ALL_FACTORS set to true all afcors of
 * prime-1 are returned in FACTORS.
 *
 * mode 0: Standard
 *	1: Make sure that at least one factor is of size qbits.
 */
static gcry_err_code_t
prime_generate_internal (int mode,
			 gcry_mpi_t *prime_generated, unsigned int pbits,
			 unsigned int qbits, gcry_mpi_t g,
			 gcry_mpi_t **ret_factors,
			 gcry_random_level_t randomlevel, unsigned int flags,
                         int all_factors,
                         gcry_prime_check_func_t cb_func, void *cb_arg)
{
  gcry_err_code_t err = 0;
  gcry_mpi_t *factors_new = NULL; /* Factors to return to the
				     caller.  */
  gcry_mpi_t *factors = NULL;	/* Current factors.  */
  gcry_mpi_t *pool = NULL;	/* Pool of primes.  */
  unsigned char *perms = NULL;	/* Permutations of POOL.  */
  gcry_mpi_t q_factor = NULL;	/* Used if QBITS is non-zero.  */
  unsigned int fbits = 0;	/* Length of prime factors.  */
  unsigned int n = 0;		/* Number of factors.  */
  unsigned int m = 0;		/* Number of primes in pool.  */
  gcry_mpi_t q = NULL;		/* First prime factor.  */
  gcry_mpi_t prime = NULL;	/* Prime candidate.  */
  unsigned int nprime = 0;	/* Bits of PRIME.  */
  unsigned int req_qbits;       /* The original QBITS value.  */
  gcry_mpi_t val_2;             /* For check_prime().  */
  unsigned int is_secret = (flags & GCRY_PRIME_FLAG_SECRET);
  unsigned int count1 = 0, count2 = 0;
  unsigned int i = 0, j = 0;

  if (pbits < 48)
    return GPG_ERR_INV_ARG;

  /* If QBITS is not given, assume a reasonable value. */
  if (!qbits)
    qbits = pbits / 3;

  req_qbits = qbits;

  /* Find number of needed prime factors.  */
  for (n = 1; (pbits - qbits - 1) / n  >= qbits; n++)
    ;
  n--;

  val_2 = mpi_alloc_set_ui (2);

  if ((! n) || ((mode == 1) && (n < 2)))
    {
      err = GPG_ERR_INV_ARG;
      goto leave;
    }

  if (mode == 1)
    {
      n--;
      fbits = (pbits - 2 * req_qbits -1) / n;
      qbits =  pbits - req_qbits - n * fbits;
    }
  else
    {
      fbits = (pbits - req_qbits -1) / n;
      qbits = pbits - n * fbits;
    }
  
  if (DBG_CIPHER)
    log_debug ("gen prime: pbits=%u qbits=%u fbits=%u/%u n=%d\n",
               pbits, req_qbits, qbits, fbits, n);

  prime = gcry_mpi_new (pbits);

  /* Generate first prime factor.  */
  q = gen_prime (qbits, is_secret, randomlevel, NULL, NULL);
  
  if (mode == 1)
    q_factor = gen_prime (req_qbits, is_secret, randomlevel, NULL, NULL);
  
  /* Allocate an array to hold the factors + 2 for later usage.  */
  factors = gcry_calloc (n + 2, sizeof (*factors));
  if (!factors)
    {
      err = gpg_err_code_from_errno (errno);
      goto leave;
    }
      
  /* Make a pool of 3n+5 primes (this is an arbitrary value).  */
  m = n * 3 + 5;
  if (mode == 1) /* Need some more (for e.g. DSA).  */
    m += 5;
  if (m < 25)
    m = 25;
  pool = gcry_calloc (m , sizeof (*pool));
  if (! pool)
    {
      err = gpg_err_code_from_errno (errno);
      goto leave;
    }

  /* Permutate over the pool of primes.  */
  do
    {
    next_try:
      if (! perms)
        {
          /* Allocate new primes.  */
          for(i = 0; i < m; i++)
            {
              mpi_free (pool[i]);
              pool[i] = NULL;
            }

          /* Init m_out_of_n().  */
          perms = gcry_calloc (1, m);
          if (! perms)
            {
              err = gpg_err_code_from_errno (errno);
              goto leave;
            }
          for(i = 0; i < n; i++)
            {
              perms[i] = 1;
              pool[i] = gen_prime (fbits, is_secret,
                                   randomlevel, NULL, NULL);
              factors[i] = pool[i];
            }
        }
      else
        {
          m_out_of_n ((char*)perms, n, m);
          for (i = j = 0; (i < m) && (j < n); i++)
            if (perms[i])
              {
                if(! pool[i])
                  pool[i] = gen_prime (fbits, 0, 1, NULL, NULL);
                factors[j++] = pool[i];
              }
          if (i == n)
            {
              gcry_free (perms);
              perms = NULL;
              progress ('!');
              goto next_try;	/* Allocate new primes.  */
            }
        }

	/* Generate next prime candidate:
	   p = 2 * q [ * q_factor] * factor_0 * factor_1 * ... * factor_n + 1. 
        */
	mpi_set (prime, q);
	mpi_mul_ui (prime, prime, 2);
	if (mode == 1)
	  mpi_mul (prime, prime, q_factor);
	for(i = 0; i < n; i++)
	  mpi_mul (prime, prime, factors[i]);
	mpi_add_ui (prime, prime, 1);
	nprime = mpi_get_nbits (prime);

	if (nprime < pbits)
	  {
	    if (++count1 > 20)
	      {
		count1 = 0;
		qbits++;
		progress('>');
		mpi_free (q);
		q = gen_prime (qbits, 0, 0, NULL, NULL);
		goto next_try;
	      }
	  }
	else
	  count1 = 0;
        
	if (nprime > pbits)
	  {
	    if (++count2 > 20)
	      {
		count2 = 0;
		qbits--;
		progress('<');
		mpi_free (q);
		q = gen_prime (qbits, 0, 0, NULL, NULL);
		goto next_try;
	      }
	  }
	else
	  count2 = 0;
    }
  while (! ((nprime == pbits) && check_prime (prime, val_2, cb_func, cb_arg)));

  if (DBG_CIPHER)
    {
      progress ('\n');
      log_mpidump ("prime    : ", prime);
      log_mpidump ("factor  q: ", q);
      if (mode == 1)
        log_mpidump ("factor q0: ", q_factor);
      for (i = 0; i < n; i++)
        log_mpidump ("factor pi: ", factors[i]);
      log_debug ("bit sizes: prime=%u, q=%u",
                 mpi_get_nbits (prime), mpi_get_nbits (q));
      if (mode == 1)
        log_debug (", q0=%u", mpi_get_nbits (q_factor));
      for (i = 0; i < n; i++)
        log_debug (", p%d=%u", i, mpi_get_nbits (factors[i]));
      progress('\n');
    }

  if (ret_factors)
    {
      /* Caller wants the factors.  */
      factors_new = gcry_calloc (n + 4, sizeof (*factors_new));
      if (! factors_new)
        {
          err = gpg_err_code_from_errno (errno);
          goto leave;
        }

      if (all_factors)
        {
          i = 0;
          factors_new[i++] = gcry_mpi_set_ui (NULL, 2);
          factors_new[i++] = mpi_copy (q);
          if (mode == 1)
            factors_new[i++] = mpi_copy (q_factor);
          for(j=0; j < n; j++)
            factors_new[i++] = mpi_copy (factors[j]);
        }
      else
        {
          i = 0;
          if (mode == 1)
            {
              factors_new[i++] = mpi_copy (q_factor);
              for (; i <= n; i++)
                factors_new[i] = mpi_copy (factors[i]);
            }
          else
            for (; i < n; i++ )
              factors_new[i] = mpi_copy (factors[i]);
        }
    }
  
  if (g)
    {
      /* Create a generator (start with 3).  */
      gcry_mpi_t tmp = mpi_alloc (mpi_get_nlimbs (prime));
      gcry_mpi_t b = mpi_alloc (mpi_get_nlimbs (prime));
      gcry_mpi_t pmin1 = mpi_alloc (mpi_get_nlimbs (prime));
      
      if (mode == 1)
        err = GPG_ERR_NOT_IMPLEMENTED;
      else
        {
          factors[n] = q;
          factors[n + 1] = mpi_alloc_set_ui (2);
          mpi_sub_ui (pmin1, prime, 1);
          mpi_set_ui (g, 2);
          do
            {
              mpi_add_ui (g, g, 1);
              if (DBG_CIPHER)
                {
                  log_debug ("checking g:");
                  gcry_mpi_dump (g);
                  log_printf ("\n");
                }
              else
                progress('^');
              for (i = 0; i < n + 2; i++)
                {
                  mpi_fdiv_q (tmp, pmin1, factors[i]);
                  /* No mpi_pow(), but it is okay to use this with mod
                     prime.  */
                  gcry_mpi_powm (b, g, tmp, prime);
                  if (! mpi_cmp_ui (b, 1))
                    break;
                }
              if (DBG_CIPHER)
                progress('\n');
            } 
          while (i < n + 2);

          mpi_free (factors[n+1]);
          mpi_free (tmp);
          mpi_free (b);
          mpi_free (pmin1);
        }
    }
  
  if (! DBG_CIPHER)
    progress ('\n');


 leave:
  if (pool)
    {
      for(i = 0; i < m; i++)
	mpi_free (pool[i]);
      gcry_free (pool);
    }
  if (factors)
    gcry_free (factors);  /* Factors are shallow copies.  */
  if (perms)
    gcry_free (perms);

  mpi_free (val_2);
  mpi_free (q);
  mpi_free (q_factor);

  if (! err)
    {
      *prime_generated = prime;
      if (ret_factors)
	*ret_factors = factors_new;
    }
  else
    {
      if (factors_new)
	{
	  for (i = 0; factors_new[i]; i++)
	    mpi_free (factors_new[i]);
	  gcry_free (factors_new);
	}
      mpi_free (prime);
    }

  return err;
}
Example #26
0
int main()
{
	int i, j, k, n, a, b, index, num_inner, max_inner, value_decimal;
	char str_a[num_digits], str_b[num_digits], palindrome[num_digits], tmp[num_digits], fmt[8];
	int len_a, len_b;
	char digit_ends[] = { '1', '3', '7', '9'};
	num = (int *)malloc(num_primes * sizeof(int));
	num2 = (int *)malloc(num_primes * sizeof(int));
	n = find_prime();
	scanf("%d %d", &a, &b);
	sprintf(str_a, "%d", a);
	sprintf(str_b, "%d", b);
	len_a = strlen(str_a);
	len_b = strlen(str_b);
	for (i = len_a; i <= len_b; i++) {
		if (i == 1) {
			for (j = 5; j <= 9; j+=2) {
				if (j < a || j > b)
					continue;
				if (check_prime(j, n))
					printf("%d\n", j);
			}
			continue;
		}
		if (i == 2) {
			for (j = 11; j <= 99; j+=22) {
				if (j < a || j > b)
					continue;
				if (check_prime(j, n))
					printf("%d\n", j);
			}
			continue;
		}
		if(i % 2 == 1) {
			num_inner = i / 2;
			max_inner = 1;
			sprintf(fmt, "%%0%dd\n", num_inner);
			for (j = 0; j < num_inner; j++)
				max_inner *= 10;
			for (index = 0; index < 4; index++) {
				palindrome[0] = digit_ends[index];
				palindrome[i - 1] = digit_ends[index];
				palindrome[i] = '\0';
				for (j = 0; j < max_inner; j++) {
					sprintf(tmp, fmt, j);
					for (k = 1; k <= i / 2; k++) {
						palindrome[k] = tmp[k - 1];
						palindrome[i - 1 - k] = palindrome[k];
					}
					sscanf(palindrome, "%d", &value_decimal);
					if (value_decimal < a)
						continue;
					if (value_decimal > b)
						break;
					if (check_prime(value_decimal, n))
						printf("%d\n", value_decimal);
				}
			}
			continue;
		}
		if ( i % 2 == 0)
			continue;
	}
	free(num);
	free(num2);
	return 0;
}
Example #27
0
/****************
 * We do not need to use the strongest RNG because we gain no extra
 * security from it - The prime number is public and we could also
 * offer the factors for those who are willing to check that it is
 * indeed a strong prime.
 *
 * mode 0: Standard
 *	1: Make sure that at least one factor is of size qbits.
 */
MPI
generate_elg_prime( int mode, unsigned pbits, unsigned qbits,
		    MPI g, MPI **ret_factors )
{
    int n;  /* number of factors */
    int m;  /* number of primes in pool */
    unsigned fbits; /* length of prime factors */
    MPI *factors; /* current factors */
    MPI *pool;	/* pool of primes */
    MPI q;	/* first prime factor (variable)*/
    MPI prime;	/* prime test value */
    MPI q_factor; /* used for mode 1 */
    byte *perms = NULL;
    int i, j;
    int count1, count2;
    unsigned nprime;
    unsigned req_qbits = qbits; /* the requested q bits size */
    MPI val_2  = mpi_alloc_set_ui( 2 );

    /* find number of needed prime factors */
    for(n=1; (pbits - qbits - 1) / n  >= qbits; n++ )
	;
    n--;
    if( !n || (mode==1 && n < 2) )
	log_fatal("can't gen prime with pbits=%u qbits=%u\n", pbits, qbits );
    if( mode == 1 ) {
	n--;
	fbits = (pbits - 2*req_qbits -1) / n;
	qbits =  pbits - req_qbits - n*fbits;
    }
    else {
	fbits = (pbits - req_qbits -1) / n;
	qbits = pbits - n*fbits;
    }
    if( DBG_CIPHER )
	log_debug("gen prime: pbits=%u qbits=%u fbits=%u/%u n=%d\n",
		    pbits, req_qbits, qbits, fbits, n  );
    prime = mpi_alloc( (pbits + BITS_PER_MPI_LIMB - 1) /  BITS_PER_MPI_LIMB );
    q = gen_prime( qbits, 0, 0 );
    q_factor = mode==1? gen_prime( req_qbits, 0, 0 ) : NULL;

    /* allocate an array to hold the factors + 2 for later usage */
    factors = m_alloc_clear( (n+2) * sizeof *factors );

    /* make a pool of 3n+5 primes (this is an arbitrary value) */
    m = n*3+5;
    if( mode == 1 )
	m += 5; /* need some more for DSA */
    if( m < 25 )
	m = 25;
    pool = m_alloc_clear( m * sizeof *pool );

    /* permutate over the pool of primes */
    count1=count2=0;
    do {
      next_try:
	if( !perms ) {
	    /* allocate new primes */
	    for(i=0; i < m; i++ ) {
		mpi_free(pool[i]);
		pool[i] = NULL;
	    }
	    /* init m_out_of_n() */
	    perms = m_alloc_clear( m );
	    for(i=0; i < n; i++ ) {
		perms[i] = 1;
		pool[i] = gen_prime( fbits, 0, 0 );
		factors[i] = pool[i];
	    }
	}
	else {
	    m_out_of_n( perms, n, m );
	    for(i=j=0; i < m && j < n ; i++ )
		if( perms[i] ) {
		    if( !pool[i] )
			pool[i] = gen_prime( fbits, 0, 0 );
		    factors[j++] = pool[i];
		}
	    if( i == n ) {
		m_free(perms); perms = NULL;
		progress('!');
		goto next_try;	/* allocate new primes */
	    }
	}

	mpi_set( prime, q );
	mpi_mul_ui( prime, prime, 2 );
	if( mode == 1 )
	    mpi_mul( prime, prime, q_factor );
	for(i=0; i < n; i++ )
	    mpi_mul( prime, prime, factors[i] );
	mpi_add_ui( prime, prime, 1 );
	nprime = mpi_get_nbits(prime);
	if( nprime < pbits ) {
	    if( ++count1 > 20 ) {
		count1 = 0;
		qbits++;
		progress('>');
                mpi_free (q);
		q = gen_prime( qbits, 0, 0 );
		goto next_try;
	    }
	}
	else
	    count1 = 0;
	if( nprime > pbits ) {
	    if( ++count2 > 20 ) {
		count2 = 0;
		qbits--;
		progress('<');
                mpi_free (q);
		q = gen_prime( qbits, 0, 0 );
		goto next_try;
	    }
	}
	else
	    count2 = 0;
    } while( !(nprime == pbits && check_prime( prime, val_2 )) );

    if( DBG_CIPHER ) {
	progress('\n');
	log_mpidump( "prime    : ", prime );
	log_mpidump( "factor  q: ", q );
	if( mode == 1 )
	    log_mpidump( "factor q0: ", q_factor );
	for(i=0; i < n; i++ )
	    log_mpidump( "factor pi: ", factors[i] );
	log_debug("bit sizes: prime=%u, q=%u", mpi_get_nbits(prime), mpi_get_nbits(q) );
	if( mode == 1 )
	    fprintf(stderr, ", q0=%u", mpi_get_nbits(q_factor) );
	for(i=0; i < n; i++ )
	    fprintf(stderr, ", p%d=%u", i, mpi_get_nbits(factors[i]) );
	progress('\n');
    }

    if( ret_factors ) { /* caller wants the factors */
	*ret_factors = m_alloc_clear( (n+2) * sizeof **ret_factors);
        i = 0;
	if( mode == 1 ) {
	    (*ret_factors)[i++] = mpi_copy( q_factor );
	    for(; i <= n; i++ )
		(*ret_factors)[i] = mpi_copy( factors[i] );
	}
	else {
	    for(; i < n; i++ )
		(*ret_factors)[i] = mpi_copy( factors[i] );
	}
    }

    if( g ) { /* create a generator (start with 3)*/
	MPI tmp   = mpi_alloc( mpi_get_nlimbs(prime) );
	MPI b	  = mpi_alloc( mpi_get_nlimbs(prime) );
	MPI pmin1 = mpi_alloc( mpi_get_nlimbs(prime) );

	if( mode == 1 )
	    BUG(); /* not yet implemented */
	factors[n] = q;
	factors[n+1] = mpi_alloc_set_ui(2);
	mpi_sub_ui( pmin1, prime, 1 );
	mpi_set_ui(g,2);
	do {
	    mpi_add_ui(g, g, 1);
	    if( DBG_CIPHER ) {
		log_debug("checking g: ");
		mpi_print( stderr, g, 1 );
	    }
	    else
		progress('^');
	    for(i=0; i < n+2; i++ ) {
		/*fputc('~', stderr);*/
		mpi_fdiv_q(tmp, pmin1, factors[i] );
		/* (no mpi_pow(), but it is okay to use this with mod prime) */
		mpi_powm(b, g, tmp, prime );
		if( !mpi_cmp_ui(b, 1) )
		    break;
	    }
	    if( DBG_CIPHER )
		progress('\n');
	} while( i < n+2 );
	mpi_free(factors[n+1]);
	mpi_free(tmp);
	mpi_free(b);
	mpi_free(pmin1);
    }
    if( !DBG_CIPHER )
	progress('\n');

    m_free( factors );	/* (factors are shallow copies) */
    for(i=0; i < m; i++ )
	mpi_free( pool[i] );
    m_free( pool );
    m_free(perms);
    mpi_free(val_2);
    mpi_free(q);
    return prime;
}