为什么不使用大于10位的数字?

时间:2015-05-07 00:39:06

标签: c rsa primes

Hello社区我有以下问题以下代码不会收敛到超过10位数的任何解决方案,并且不知道问题出在哪里因为知道数字是素数将会遇到Fermat的小一个调用函数中的定理。

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

unsigned long exp_mod(unsigned long x, unsigned long y, unsigned long n)
{
    unsigned long s,t,u;
    int i;
    s=1; t=x; u=y;
    while(u) {
        if (u&1) s=(s*t)%n;
        u>>=1;
        t=(t*t)%n;
    }
    return s;
}

int main(){
    unsigned long number,a,b;
    int i;
    printf("introduce number to test\n");
    scanf("%lu",&a);
    number=a;
    srand((unsigned int)time(0));

    while (1) {
        a=rand()%(number-1)+2;//0<a<number
        b=exp_mod(a,number-1,number);
        if ( b==1 ) {
            printf ("by Fermat:  %lu is prime\n",number);
            break;
        }
    }
    return 0;
}

有什么建议吗?问候

2 个答案:

答案 0 :(得分:2)

在大多数编译器和系统上,unsigned long的大小是32位,所以它大约是4 * 10 ^ 9 - 所以这就是它无法处理10位数字的原因。 只需将unsigned long更改为unsigned long long int即可。

答案 1 :(得分:2)

这里的代码然后为您提出的解决方案谢谢!

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

main()
{
 mpz_t b;
 mpz_init(b);
 int escero;
 unsigned long numero,a;
…
 printf("Introduzca el numero a testear\n");
 scanf("%lu",&a);
 numero=a;
 srand((unsigned int)time(0));
 mpz_t A,P,P1;
 mpz_init(A); mpz_init(P); mpz_init(P1);
…

 while (1) {
        a=rand()%(numero-1)+2;//0<a<numero
        mpz_set_ui(A,a);
        mpz_set_ui(P1, (numero-1) );
        mpz_set_ui(P,numero);
        mpz_powm( b, A, P1, P);//b=exp_mod(a,numero-1,numero);
        //gmp_printf("a^p-1 [mod p] = %Zd\n",b);
        if ( !mpz_cmp_d(b,1) ) {
…
         printf ("%lu es testigo por Fermat de que %lu es primo\n",a,numero);
         break;
         }
        }
 return 0;
}

再次感谢社区!!

相关问题