题目:
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
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
Note
In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.
In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.
In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
解题报告:首先需要理解题目所说的素矩阵,是个什么东西,就是有一行或者一列全为素数的矩阵,就叫素矩阵,首先利用素数筛,将所有素数打出来,然后对矩阵,分别进行行列遍历,寻找每行每列的一个更新值,就是将所有不是素数的数更新为素数的值,遇到一个点不是素数的话,咱们就进行+1操作并记录,直到他变成素数为止。
ac代码:
#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=1e5+1000;
int n,m;
int mp[1005][1005];
int a[1005][1005],b[1005][1005];
int prime[maxn];
void db()
{
prime[0]=1;
prime[1]=1;
for(int i=2;i<=maxn;i++)
for(int j=i*2;j<=maxn;j+=i)
{
if(!prime[j])
prime[j]=1;
}
}
int main()
{
db();
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
scanf("%d",&mp[i][j]);
a[i][j]=b[i][j]=mp[i][j];
}
int ans=99999999;
int cnt;
for(int i=0;i<n;i++)
{
cnt=0;
for(int j=0;j<m;j++)
{
while(prime[a[i][j]])
{
cnt++;
a[i][j]++;
}
}
ans=min(ans,cnt);
}
for(int j=0;j<m;j++)
{
cnt=0;
for(int i=0;i<n;i++)
{
while(prime[b[i][j]])
{
cnt++;
b[i][j]++;
}
}
ans=min(cnt,ans);
}
printf("%d\n",ans);
}