将如下代码转成C#语言代码 import math def relatively_prime(a,b): # a > b while b != 0: temp = b b = a%b a = temp if a==1: return True else: return False def millerRabin(num): if num%2 ==0: return False flag = True Subsquare = 0 temp = num - 1 while True: temp = temp / 2 Subsquare += 1 if temp % 2 != 0: break b=[] # 存放所求整数(num)的原根 count = 0 for i in range(2,num-1):# g^(P-1) = 1 (mod P) if relatively_prime(num,i): b.append(i) count += 1 if count == 5: # 控制检测次数 break for i in b: two = 0 while True: if (i**temp)**(2**two)%num == 1 or (i**temp)**(2**two)%num == num-1: flag = True break else: two += 1 if two == Subsquare: flag = False break if flag == False: break # 如果存在一次不满足条件,则退出循环 return flag num = input(u"请输入要进行Miller-Rabin算法检测的数:") if millerRabin(num): print u"{0}大概率是素数".format(num) else: print u"{0}是合数 ".format(num)
时间: 2024-04-25 17:26:18 浏览: 123
using System;
namespace MillerRabin
{
class Program
{
static bool RelativelyPrime(int a, int b)
{
while (b != 0)
{
int temp = b;
b = a % b;
a = temp;
}
if (a == 1)
{
return true;
}
else
{
return false;
}
}
static bool MillerRabin(int num)
{
if (num % 2 == 0)
{
return false;
}
bool flag = true;
int subsquare = 0;
int temp = num - 1;
while (true)
{
temp = temp / 2;
subsquare += 1;
if (temp % 2 != 0)
{
break;
}
}
int[] b = new int[5]; // 存放所求整数(num)的原根
int count = 0;
for (int i = 2; i < num - 1; i++)
{
if (RelativelyPrime(num, i))
{
b[count] = i;
count += 1;
if (count == 5) // 控制检测次数
{
break;
}
}
}
for (int i = 0; i < 5; i++)
{
int two = 0;
while (true)
{
if (Math.Pow(b[i], temp * Math.Pow(2, two)) % num == 1 || Math.Pow(b[i], temp * Math.Pow(2, two)) % num == num - 1)
{
flag = true;
break;
}
else
{
two += 1;
if (two == subsquare)
{
flag = false;
break;
}
}
}
if (flag == false)
{
break; // 如果存在一次不满足条件,则退出循环
}
}
return flag;
}
static void Main(string[] args)
{
Console.WriteLine("请输入要进行Miller-Rabin算法检测的数:");
int num = Convert.ToInt32(Console.ReadLine());
if (MillerRabin(num))
{
Console.WriteLine("{0}大概率是素数", num);
}
else
{
Console.WriteLine("{0}是合数", num);
}
Console.ReadLine();
}
}
}
阅读全文