codeForces 271B--素数矩阵

 

Description

You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.

You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not.

A matrix is prime if at least one of the two following conditions fulfills:

  • the matrix has a row with prime numbers only;
  • the matrix has a column with prime numbers only;

Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.

Input

The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly.

Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105.

The numbers in the lines are separated by single spaces.

Output

Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.

Sample Input

Input
3 3
1 2 3
5 6 1
4 4 1
Output
1
Input
2 3
4 8 8
9 2 9
Output
3
Input
2 2
1 3
4 2
Output
0
//此题应该说是素数打表的应用。。。不多赘述
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
bool vis[100108];//用来标记素数
#define maxn 100100
int matrix[508][508];
int gosu[508][508];//如果是一个不是数,把他转换为素数需要多少步
int gosh[508];
int gosl[508];
int main()
{
	for(int i=2;i*i<=maxn;i++)
	{
		if(!vis[i])
		{
			for(int j=i*i;j<=maxn;j+=i)
			{
				vis[j]=1;
			}
		}
	}
	vis[1]=1;
	int n,m;
	while(scanf("%d%d",&n,&m)==2)//所有数组的初始化问题
	{
		memset(gosu,0,sizeof(gosu));
		memset(gosh,0,sizeof(gosh));
		memset(gosl,0,sizeof(gosl));
		for(int i=1;i<=n;i++)
		{
			for(int j=1;j<=m;j++)
			{
				scanf("%d",&matrix[i][j]);
				int z=matrix[i][j];
				if(vis[z])//如果输进去的不是个素数
				{
					for(int k=z;k<=maxn;k++)
					{
						if(vis[k])
						{
							gosu[i][j]++;
						}
						else break;
					}
				}
			}
		}
		for(int i=1;i<=n;i++)
		{
			for(int j=1;j<=m;j++)
			{
				gosh[i]+=gosu[i][j];
			}
		}
		for(int i=1;i<=m;i++)
		{
			for(int j=1;j<=n;j++)
			{
				gosl[i]+=gosu[j][i];
			}
		}
		sort(gosh+1,gosh+n+1);
		sort(gosl+1,gosl+m+1);
		int feishall=gosh[1],feislall=gosl[1];
		cout<<(feishall>feislall?feislall:feishall)<<endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值