CC

自然万物都趋向从有序变得无序

0%

Prime Matrix CodeForces - 271B

题目链接:点我

题目


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.

Example
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,问最少需要多少次这样的操作才能把这个矩阵变成一个素数矩阵.

思路:

素数打表,然后直接暴力计算,最后输出最小值

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<iostream>
using namespace std;

const int maxn = 1e5 +10;
bool vis[maxn];
int pri[maxn];
int num = 0;
int w[502][502];
int a[502];
int b[502];

void prime(){
memset(vis,false,sizeof(vis));
for(int i = 2; i < maxn; ++i){
if(!vis[i]) pri[num++] = i;
for(int j = 0; j < num && i * pri[j] < maxn; ++j){
vis[i * pri[j]] = true;
if( i % pri[j] == 0) break;
}
}
vis[1] = vis[0] =true;
}

int main(){
int n, m;
prime();
scanf("%d %d", &n, &m);
bool flag = false;
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= m; ++j){
scanf("%d", &w[i][j]);
if(vis[w[i][j]]){
int t = lower_bound(pri,pri+num,w[i][j]) - pri;
//查找离这个树最近的一个比它大的素数.
a[i] += pri[t] - w[i][j];
b[j] += pri[t] - w[i][j];
}
}sort(a+1,a+1+n);
sort(b+1,b+1+m);
int ans= min(a[1],b[1]);
printf("%d\n",ans);
return 0;
}