1. 程式人生 > >271B Prime Matrix (素數打表)

271B Prime Matrix (素數打表)

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.

Examples

input

Copy

3 3
1 2 3
5 6 1
4 4 1

output

Copy

1

input

Copy

2 3
4 8 8
9 2 9

output

Copy

3

input

Copy

2 2
1 3
4 2

output

Copy

0

解題說明:題目中一個素數矩陣的要求是隻有一行元素都是素數,或只有一列元素都是素數。這裡可以找出矩陣中所有元素與其最接近的素數直接的差值(素數要比該元素大才行),然後針對每一行,每一列求出一個差值最小的。為此,需要先儲存一個較大的素數陣列,這個可以預先計算出來。考慮到矩陣中元素的值不會超過10^5,那素數陣列的大小也就是這個數量級即可。最後找出一列或一行差值最小的輸出。

素數打表的時候用到了線性篩

AC程式碼:

#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int prime[100010],map[510][510]; 
int sumc[510],sumr[510];
int tag[100010];
int cnt;
void Prime(){   //線性篩 
	memset(tag,0,sizeof(tag));
	cnt=0;
	tag[0]=tag[1]=1;
	for(int i = 2; i<100010; i++){
		if(!tag[i])
			prime[cnt++]=i;
		for(int j=0;j<cnt && prime[j]*i<100010; j++){
			tag[i*prime[j]] = 1;
			if(i % prime[j]==0)
				break;
		}
	}
}

int main()
{
	int n,m,i,j,k;
	scanf("%d%d",&n,&m);
	Prime();
	memset(map,0,sizeof(map));
	memset(sumc,0,sizeof(sumc));
	memset(sumr,0,sizeof(sumr));
	for(i=0;i<n;i++)
	for(j=0;j<m;j++)
	{
		scanf("%d",&map[i][j]);
	}
	for(i=0;i<n;i++)
	{
		int sum=0;
		for(j=0;j<m;j++)
		{
			if(tag[map[i][j]])//如果輸入的數不是素數 
			{
				int t=lower_bound(prime,prime+cnt,map[i][j])-prime;
				sumr[j]+=(prime[t]-map[i][j]);
				sumc[i]+=(prime[t]-map[i][j]);
			 } 
		}
	}
	
	sort(sumr,sumr+m);
	sort(sumc,sumc+n);
	//cout<<sumr[0];
	cout<<((sumr[0]<sumc[0])?sumr[0]:sumc[0])<<endl;
	return 0;
}