You are on page 1of 2

#include<stdio.

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

int power(int a, int b, int n)


{
int res = 1;

while (b &gt; 0)
{
if (b % 2 == 1)
{
res = (res * a) % n;
}

a = (a * a) % n;

b = b / 2;
}

return res;
}

int witness(int a, int n)


{
int t = 0, u = n - 1;

while (u % 2 == 0)
{
t++;
u /= 2;
}

int x = power(a, u, n);

if (x == 1 || x == n - 1)
{
return 0;
}

for (int i = 0; i &lt; t - 1; i++)


{
x = (x * x) % n;

if (x == n - 1)
{

return 0;
}
}

return 1;
}

int is_prime(int n, int k)


{
if (n == 2 || n == 3)
{
return 1;
}

if (n &lt;= 1 || n % 2 == 0)
{
return 0;
}

for (int i = 0; i &lt; k; i++)


{
int a = rand() % (n - 3) + 2;

if (witness(a, n))
{
return 0;
}
}

return 1;
}

int main()
{
int n, k;

printf(&quot;Enter the number to be tested: &quot;);


scanf(&quot;%d&quot;, &amp;n);

printf(&quot;Enter the number of iterations: &quot;);


scanf(&quot;%d&quot;, &amp;k);

srand(time(NULL));

if (is_prime(n, k))
{
printf(&quot;%d is prime.\n&quot;, n);
}
else
{
printf(&quot;%d is composite.\n&quot;, n);
}

You might also like