51nod 1186 质数检测 V2 质数检测(四种方式)

本文详细介绍了四种不同的质数检测算法,包括适用于小数据范围的暴力检测、C++版的Miller_Rabin测试、以及两种适用于大数据范围的Java大数版Miller_Rabin算法,提供了丰富的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 题目链接:

http://www.51nod.com/Challenge/Problem.html#problemId=1186

1186 质数检测 V2

给出1个正整数N,检测N是否为质数。如果是,输出"Yes",否则输出"No"。

 收起

输入

输入一个数N(2 <= N <= 10^30)

输出

如果N为质数,输出"Yes",否则输出"No"。

输入样例

17

输出样例

Yes

第一种,适用于数据范围小的----直接暴力

This is the code:

#include<bits/stdc++.h>
using namespace std;
bool IsPrime(int x)
{
    for(int i=2;i<=sqrt(x);++i)
        if(x%i==0)
            return false;
    return true;
}
int main()
{
    int n;
    sccanf("%d",&n);
    if(IsPrime(n))
        printf("YES\n");
    else
        printf("NO\n");
    return 0;
}

第二种,适用于1e18的数据范围 C++版的Miller_Rabin测试素数

This is the code:

#include<bits/stdc++.h>
using namespace std;
#define LL long long
LL modular_exp(LL a,LL n,LL mod)
{
    LL ret=1;
    a%=mod;
    while(n)
    {
        if(n&1)
            ret=a*ret%mod,n--;
        a=a*a%mod;
        n>>=1;
    }
    return ret;;
}
bool miller_rabin1(LL n)//误差很大,直接使用费马定理判断
{
    if(n==0||n==1)
        return false;
    if(n==2)
        return true;
    for(LL i=2; i<10; ++i)
    {
        LL a=rand()%(n-2)+2;
        if(modular_exp(a,n,n)!=a)
            return false;
    }
    return true;
}
LL gcd(LL a,LL b)//求最大公约数
{
    return b?gcd(b,a%b):a;
}
LL multi(LL a,LL b,LL mod)//快速加法求模
{
    LL ret=0;
    while(b)
    {
        if(b&1)
            ret=(ret+a)%mod,b--;
        a=(a+a)%mod;
        b>>=1;
    }
    return ret;
}
LL power(LL a,LL b,LL mod)
{
    LL ret=1;
    a%=mod;
    while(b)
    {
        if(b&1)
            ret=multi(ret,a,mod),b--;
        a=multi(a,a,mod);
        b>>=1;
    }
    return ret;
}
bool miller_rabin2(LL n)//费马定理和二次探测原理判断素数
{
    if(n==2)
        return true;
    if(n<2||!(n&1))
        return false;
    LL m=n-1;
    LL cnt=0;
    while(!(m&1))
    {
        ++cnt;
        m>>=1;
    }
    LL Times=10;
    for(LL i=0; i<Times; ++i)//Times==10
    {
        LL a=rand()%(n-1)+1;
        LL x=power(a,m,n);
        LL y=0;
        for(LL j=0; j<cnt; ++j)
        {
            y=multi(x,x,n);
            if(y==1&&x!=1&&x!=n-1)
                return false;
            x=y;
        }
        if(y!=1)
            return false;
    }
    return true;
}
int main()
{
    srand(time(NULL));
    LL n;
    scanf("%lld",&n);
    if(miller_rabin1(n))
        printf("YES\n");
    else
        printf("NO\n");
}

第三种 适用于大数 java大数版Miller_Rabin

This is the code:

import java.io.*;
import java.math.*;
import java.util.*;
import java.text.*;
public class Main{

	public static void main(String[] args) {
		Scanner cin = new Scanner(new BufferedInputStream(System.in));
		BigInteger N;
		N = cin.nextBigInteger();
		if(IsPrime(N))
		{
			System.out.println("Yes");
		}
		else
			System.out.println("No");
	}
	public static Boolean IsPrime(BigInteger num)
	{
		if(num.compareTo(BigInteger.valueOf(2)) == 0)
			return true;
		if((num.mod(BigInteger.valueOf(2)).compareTo(BigInteger.valueOf(0)) == 0) || (num.compareTo(BigInteger.valueOf(1)) == 0))
			return false;
		BigInteger num_1 = num.subtract(BigInteger.valueOf(1));
		int s = 0;
		while(num_1.mod(BigInteger.valueOf(2)).compareTo(BigInteger.valueOf(0)) == 0)
		{
			num_1 = num_1.divide(BigInteger.valueOf(2));
			++ s;
		}
		Random ran = new Random();
		for(int i = 0; i < 10; ++ i)
		{
			BigInteger a = BigInteger.valueOf(2); 
			BigInteger b = BigInteger.valueOf(Math.abs(ran.nextLong())).mod(num.subtract(BigInteger.valueOf(3)));
			a = a.add(b);
			BigInteger x = FastPowerMod(a,num_1,num);
			if(x.compareTo(BigInteger.valueOf(1)) != 0 && x.compareTo((num.subtract(BigInteger.valueOf(1)))) != 0)
			{
				Boolean flag = false;
				for(int j = 1; j < s; ++ j)
				{
					BigInteger t = x.multiply(x).mod(num);
					if(t.compareTo(num.subtract(BigInteger.valueOf(1))) == 0)
					{
						flag = true;
						break;
					}
					x = t;
				}
				if(flag)
					continue;
				return false;
			}
		}
		return true;
	}
	public static BigInteger FastPowerMod(BigInteger a,BigInteger m,BigInteger n)
	{
		BigInteger ans = BigInteger.valueOf(1);
		BigInteger tmp = a;
		while(m.compareTo(BigInteger.valueOf(0)) == 1)
		{
			if(m.mod(BigInteger.valueOf(2)).compareTo(BigInteger.valueOf(1)) == 0)
			{
				ans = ans.multiply(tmp).mod(n);
			}
			tmp = tmp.multiply(tmp).mod(n);
			m = m.divide(BigInteger.valueOf(2));
		}
		return ans.mod(n);
	}
}

第四种 适用于大数 java大数版 Miller_Rabin 集成的函数

This is the code:


import java.util.Scanner;
import java.math.*;
 
public class Main {
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		BigInteger x;
			x=cin.nextBigInteger();
			if(x.isProbablePrime(1))
				System.out.println("Yes");
			else
				System.out.println("No");
	}
 
}

 

 

 

 

 

 

题目 51nod 3478 涉及一个矩阵问题,要求通过最少的操作次数,使得矩阵中至少有 `RowCount` 行和 `ColumnCount` 列是回文的。解决这个问题的关键在于如何高效地枚举所有可能的行和列组合,并计算每种组合所需的操作次数。 ### 解法思路 1. **预处理每一行和每一列变为回文所需的最少操作次数**: - 对于每一行,计算将其变为回文所需的最少操作次数。这可以通过比较每对对称位置的值是否相同来完成。 - 对于每一列,计算将其变为回文所需的最少操作次数,方法同上。 2. **枚举所有可能的行和列组合**: - 由于 `N` 和 `M` 的最大值为 8,因此可以枚举所有可能的行组合和列组合。 - 对于每一种组合,计算其所需的最少操作次数,并取最小值。 3. **计算操作次数**: - 对于每一种组合,需要计算哪些行和列需要修改,并且注意行和列的交叉点可能会重复计算,因此需要去重。 ### 代码实现 以下是一个可能的实现方式,使用了枚举和位运算来处理组合问题: ```python def min_operations_to_palindrome(matrix, row_count, col_count): import itertools N = len(matrix) M = len(matrix[0]) # Precompute the cost to make each row a palindrome row_cost = [] for i in range(N): cost = 0 for j in range(M // 2): if matrix[i][j] != matrix[i][M - 1 - j]: cost += 1 row_cost.append(cost) # Precompute the cost to make each column a palindrome col_cost = [] for j in range(M): cost = 0 for i in range(N // 2): if matrix[i][j] != matrix[N - 1 - i][j]: cost += 1 col_cost.append(cost) min_total_cost = float('inf') # Enumerate all combinations of rows and columns rows = list(range(N)) cols = list(range(M)) from itertools import combinations for row_comb in combinations(rows, row_count): for col_comb in combinations(cols, col_count): # Calculate the cost for this combination cost = 0 # Add row costs for r in row_comb: cost += row_cost[r] # Add column costs for c in col_comb: cost += col_cost[c] # Subtract the overlapping cells for r in row_comb: for c in col_comb: # Check if this cell is part of the palindrome calculation if r < N // 2 and c < M // 2: if matrix[r][c] != matrix[r][M - 1 - c] and matrix[N - 1 - r][c] != matrix[N - 1 - r][M - 1 - c]: cost -= 1 min_total_cost = min(min_total_cost, cost) return min_total_cost # Example usage matrix = [ [0, 1, 0], [1, 0, 1], [0, 1, 0] ] row_count = 2 col_count = 2 result = min_operations_to_palindrome(matrix, row_count, col_count) print(result) ``` ### 代码说明 - **预处理成本**:首先计算每一行和每一列变为回文所需的最少操作次数。 - **枚举组合**:使用 `itertools.combinations` 枚举所有可能的行和列组合。 - **计算成本**:对于每一种组合,计算其成本,并考虑行和列交叉点的重复计算问题。 ### 复杂度分析 - **时间复杂度**:由于 `N` 和 `M` 的最大值为 8,因此枚举所有组合的时间复杂度为 $ O(N^{RowCount} \times M^{ColCount}) $,这在实际中是可接受的。 - **空间复杂度**:主要是存储预处理的成本,空间复杂度为 $ O(N + M) $。 ### 相关问题 1. 如何优化矩阵中行和列的枚举组合以减少计算时间? 2. 在计算行和列的交叉点时,如何更高效地处理重复计算的问题? 3. 如果矩阵的大小增加到更大的范围,如何调整算法以保持效率? 4. 如何处理矩阵中行和列的回文条件不同时的情况? 5. 如何扩展算法以支持更多的操作类型,例如翻转某个区域的值?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值