Search is not available for this dataset
name
stringlengths 2
112
| description
stringlengths 29
13k
| source
int64 1
7
| difficulty
int64 0
25
| solution
stringlengths 7
983k
| language
stringclasses 4
values |
---|---|---|---|---|---|
271_B. 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
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. | 2 | 8 | from sys import stdin,stdout
input=stdin.readline
import math,bisect
num = 102001
prime=[1]*num
prime[1]=0
prime[0]=0
for i in range(2,num):
j=i
while(j+i<num):
j+=i
prime[j]=0
l=[]
n,m=map(int,input().split())
for i in range(n):
t=list(map(int,input().split()))
l.append(t)
ans=60000000
for i in range(n):
tot=0
for j in range(m):
result=l[i][j]
for k in range(result,num):
if prime[k]==1:
tot+=k-result
break
ans=min(ans,tot)
for j in range(m):
tot=0
for i in range(n):
result=l[i][j]
for k in range(result,num):
if prime[k]==1:
tot+=k-result
break
ans=min(ans,tot)
print(ans)
| PYTHON3 |
271_B. 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
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. | 2 | 8 | from bisect import bisect_left as bisect
def primes(n):
correction = (n%6>1)
n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6]
sieve = [True] * (n/3)
sieve[0] = False
for i in xrange(int(n**0.5)/3+1):
if sieve[i]:
k=3*i+1|1
sieve[ ((k*k)/3) ::2*k]=[False]*((n/6-(k*k)/6-1)/k+1)
sieve[(k*k+4*k-2*k*(i&1))/3::2*k]=[False]*((n/6-(k*k+4*k-2*k*(i&1))/6-1)/k+1)
return [2,3] + [3*i+1|1 for i in xrange(1,n/3-correction) if sieve[i]]
p = primes(100005)
n,m = [int(c) for c in raw_input().split()]
g = [[int(c) for c in raw_input().split()] for i in xrange(n)]
for i in xrange(n):
for j in xrange(m):
g[i][j] = p[bisect(p,g[i][j])]-g[i][j]
print min(min(sum(r) for r in g), min(sum(r) for r in zip(*g))) | PYTHON |
271_B. 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
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. | 2 | 8 | import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
import java.util.TreeMap;
public class B {
static final int MAX = 100500;
public static void main(String[] args) {
doIt();
}
static void doIt() {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
boolean[] prime = new boolean[MAX];
Arrays.fill(prime, true);
prime[0] = prime[1] = false;
TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
for (int i = 2; i < prime.length; i++) {
if(prime[i]){
map.put(i, 0);
for (int j = i*2; j < prime.length; j += i) {
prime[j] = false;
}
}
}
int n = sc.nextInt();
int m = sc.nextInt();
int[][] matrix = new int[n][m];
int[] rowsum = new int[n];
int[] clmsum = new int[m];
for (int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
int e = sc.nextInt();
if(prime[e]) matrix[i][j] = 0;
else matrix[i][j] = map.ceilingKey(e) - e;
rowsum[i] += matrix[i][j];
clmsum[j] += matrix[i][j];
}
}
Arrays.sort(rowsum);
Arrays.sort(clmsum);
System.out.println(Math.min(rowsum[0], clmsum[0]));
}
} | JAVA |
271_B. 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
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. | 2 | 8 | def sieve(mx):
a = [0] * (mx + 1)
a[0] = a[1] = 1
for (i, e) in enumerate(a):
if e == 0:
for n in range(i*i, mx + 1, i):
a[n] = 1
return a
p = sieve(10**5 + 100)
for i in range(10**5 + 99, 0, -1):
p[i] *= p[i+1] +1
n,m = map(int, input().split())
cols = [0]*m
mm = 10**7
for i in range(n):
row = list(map(int, input().split()))
row_sum = 0
for a, j in enumerate(row):
tt = p[j]
row_sum += tt
cols[a] += tt
mm = min(mm, row_sum)
print(min(min(cols), mm)) | PYTHON3 |
271_B. 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
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. | 2 | 8 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
boolean[] P = new boolean[1000000];
Arrays.fill(P, true);
P[0] = P[1] = false;
for(int i = 2; i * i < P.length; i++)if(P[i])
for(int j = i * i; j < P.length; j += i)
P[j] = false;
// int prev = 2, max = 0;
// for(int i = 3; i < P.length; i++)if(P[i]){
// max = Math.max(max, i - prev);
// prev = i;
// }
//
// System.out.println(max);
InputReader r = new InputReader(System.in);
int N = r.nextInt();
int M = r.nextInt();
int[][] a = new int[N][M];
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++){
int x = r.nextInt();
int cnt = 0;
for(int p = x;; p++, cnt++)
if(P[p])break;
a[i][j] = cnt;
}
int min = Integer.MAX_VALUE;
for(int i = 0; i < N; i++){
int s = 0;
for(int j = 0; j < M; j++)
s += a[i][j];
min = Math.min(min, s);
}
for(int j = 0; j < M; j++){
int s = 0;
for(int i = 0; i < N; i++)
s += a[i][j];
min = Math.min(min, s);
}
System.out.println(min);
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| JAVA |
271_B. 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
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. | 2 | 8 | import java.math.*;
import java.util.*;
import java.io.*;
import static java.lang.System.*;
public class Solution {
public static void main(String[] args) throws IOException
{
Scanner in= new Scanner(System.in);
int n,m;
int cnt=0;
int a[][] = new int[501][501];
int b[][] = new int[501][501];
int c[][] = new int[501][501];
boolean er[] = new boolean[110000];
n=Integer.parseInt(in.next());
m=Integer.parseInt(in.next());
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
a[i][j] = Integer.parseInt(in.next());
}
}
er[0] = true;
er[1] = true;
er[2] = false;
for(int i=2;i<110000;i++)
{
if (er[i]==false)
{
for(int j=2*i;j<110000;j+=i)
{
er[j] = true;
}
}
}
int lst[] = new int[100000];
for(int i=2;i<110000;i++)
{
if (er[i]==false) {lst[cnt++] = i;}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
int x = a[i][j];
/*int l = 0, r = cnt;
int mid=0;
while(r-l>0)
{
mid = (r-l)/2;
if (x==lst[mid]) break;
if (x<lst[mid]) r = mid; else l = mid;
}
if (x==lst[mid]) b[i][j] = 0;
else b[i][j] = lst[r] - x;*/
while (er[x]==true)
{
x++;
}
b[i][j] = x - a[i][j];
}
}
int ans = 1000000;
for(int i=0;i<n;i++)
{
int sum = 0;
for(int j=0;j<m;j++)
{
sum+=b[i][j];
}
if (sum<ans) ans = sum;
}
for(int i=0;i<m;i++)
{
int sum = 0;
for(int j=0;j<n;j++)
{
sum+=b[j][i];
}
if (sum<ans) ans = sum;
}
out.println(ans);
}
}
| JAVA |
271_B. 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
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. | 2 | 8 | x,y=map(int,raw_input().split())
Maxprimos = 100100
primos=[True]*Maxprimos
primos[0]=False
primos[1]=False
marked={}
for i in range(2,Maxprimos):
if primos[i]:#Los vamos a marcar
for j in range(i+i,Maxprimos,i):
primos[j]=False
matriz=[]
for i in range(x):
matriz.append(map(int,raw_input().split()))
for j in range(len(matriz[i])):
z = matriz[i][j]
if z not in marked:
while not primos[z]:
z+=1
marked[matriz[i][j]]=z
matriz[i][j]=(z-matriz[i][j])#pasos para volver el numero primo
else:
matriz[i][j]=(marked[matriz[i][j]]-matriz[i][j])
row=[]
col=[]
for i in range(x):#para filas
temp=sum(matriz[i])
row.append(temp)
for i in range(y):
tempCol=[]
for j in range(x):
tempCol.append(matriz[j][i])
temp=sum(tempCol)
col.append(temp)
rowMin=min(row)
colMin=min(col)
print min(colMin,rowMin) | PYTHON |
271_B. 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
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. | 2 | 8 | import math
n, m = input().split(" ")
line = int(n)
column = int(m)
limit = 100025
primes_list = [True for i in range(limit + 1)]
next_prime_distance = [0 for i in range(200000)]
def sieve_primes():
primes_list[0] = primes_list[1] = False
for i in range(2, int(math.sqrt(limit))):
if primes_list[i]:
j = 2
while i * j <= limit:
primes_list[i*j] = False
j += 1
def next_prime():
for i in range(limit - 1, -1, -1):
if primes_list[i]:
next_prime_distance[i] = 0
else:
next_prime_distance[i] = 1 + next_prime_distance[i + 1]
sieve_primes()
next_prime()
matrix = []
for row in range(line):
number = input().split(" ")
matrix.append([int(char) for char in number])
r = [0]*line
c = [0]*column
for i in range(line):
for j in range(column):
value = int(matrix[i][j])
distance = next_prime_distance[value]
r[i] += distance
c[j] += distance
less_row = min(r)
less_column = min(c)
print(min(less_row, less_column))
| PYTHON3 |
271_B. 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
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. | 2 | 8 | import java.io.*;
import java.math.*;
import java.util.*;
public class Task {
private static int[] primes;
private static int findNext(int a)
{
if(primes[primes.length/2] > a)
return findNext(a, 0, primes.length/2);
else if(primes[primes.length/2] < a)
return findNext(a, primes.length/2, primes.length-1);
return primes[primes.length/2];
}
private static int findNext(int a, int l, int r)
{
if(l + 1 == r)
if(primes[l] < a)
return primes[r];
else return primes[l];
else if( l == r)
return primes[r];
if(primes[(l+r)/2] > a)
return findNext(a, l, (l+r)/2);
else if(primes[(l+r)/2] < a)
return findNext(a, (l+r)/2, r);
return primes[(l+r)/2];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
/**
* ########################
* Solution
*/
ArrayList<Integer> p = new ArrayList<Integer>();
boolean[] a = new boolean[101001];
Arrays.fill(a, true);
for(int i = 2; i*i <= 101000; i++)
{
if(a[i])
{
for(int j = i*i; j <= 101000; j += i)
{
if(a[j])
a[j] = false;
}
}
}
for(int i = 2; i < 101000; i++)
{
if(a[i])
p.add(i);
}
p.trimToSize();
primes = new int[p.size()];
int k = 0;
for(Iterator<Integer> it = p.iterator(); it.hasNext();)
{
int temp = it.next();
primes[k++] = temp;
}
int n = sc.nextInt();
int m = sc.nextInt();
int[][] t = new int[n][m];
int[][] d = new int[n][m];
for(int i = 0; i < n; i++)
Arrays.fill(d[i], -1);
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
t[i][j] = sc.nextInt();
d[i][j] = findNext(t[i][j]) - t[i][j];
}
}
int[] row = new int[n];
int[] col = new int[m];
int min_row = 0;
int min_col = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
row[i] += d[i][j];
}
if(row[i] < row[min_row])
min_row = i;
}
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
col[i] += d[j][i];
}
if(col[i] < col[min_col])
min_col = i;
}
out.println(Math.min(row[min_row], col[min_col]));
/**
* Solution
* ########################
*/
out.flush();
}
} | JAVA |
271_B. 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
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. | 2 | 8 | import java.util.*;
public class CF271B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] prime = new int[1000000];
int size = 0;
prime[size++] = 2;
for (int i = 3; i <= 200000; i+=2)
if (isPrime(i))
prime[size++] = i;
int n = sc.nextInt(), m = sc.nextInt();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = sc.nextInt();
int min = Integer.MAX_VALUE;
/*for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
System.out.println(a[i][j] + " " + binarySearch(prime, 0, size, a[i][j]));*/
for (int r = 0; r < n; r++) {
int add = 0;
for (int c = 0; c < m; c++)
add += binarySearch(prime, 0, size, a[r][c]) - a[r][c];
if (add < min) min = add;
}
for (int c = 0; c < m; c++) {
int add = 0;
for (int r = 0; r < n; r++)
add += binarySearch(prime, 0, size, a[r][c]) - a[r][c];
if (add < min) min = add;
}
System.out.println(min);
}
static boolean isPrime(int a) {
for (int i = 2; i*i <= a; i++)
if (a%i == 0) return false;
return true;
}
static int binarySearch (int[] a, int low, int high, int x) {
if (low > high) return a[low];
int mid = (low + high)/2;
if (x == a[mid]) return a[mid];
else if (x < a[mid]) return binarySearch(a, low, mid-1, x);
return binarySearch(a, mid+1, high, x);
}
}
| JAVA |
271_B. 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
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. | 2 | 8 | #CRIVO
ncrivo = 1000000
crivo = [True for i in xrange(ncrivo)]
crivo[0] = crivo[1] = False
for i in xrange(2, ncrivo):
if not crivo[i]:
continue
for j in range(i * i, ncrivo, i):
crivo[j] = False
#lendo dados
n, m = map(int, raw_input().split())
data = []
for i in xrange(n):
data.append(map(int, raw_input().split()))
#frequencia
contador = [0 for i in xrange(200000)]
contador[100000] = 3
for i in xrange(99999, -1, -1):
if crivo[i]:
contador[i] = 0
#print contador[i]
else:
contador[i] = 1 + contador[i+1]
resultado = 100000
for i in xrange(n):
soma = 0
for j in xrange(m):
soma += contador[data[i][j]]
resultado = min(resultado, soma)
for i in xrange(m):
soma = 0
for j in xrange(n):
soma += contador[data[j][i]]
#print soma
resultado = min(resultado, soma)
print resultado
| PYTHON |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int a[600][600];
bool isprime(int x) {
if (x == 1) return 0;
if (x == 2) return 1;
for (int i = 2; i * i <= x; i++) {
if (x % i == 0) return 0;
}
return 1;
}
int v[600], h[600];
bool pr[100007];
vector<int> prr;
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
cin >> a[i][j];
}
pr[1] = 0;
pr[2] = 1;
for (int i = 2; i < 100007; i++) pr[i] = 1;
for (int i = 2; i < 100007; i++) {
if (pr[i]) {
prr.push_back(i);
for (int j = i + i; j < 100007; j += i) pr[j] = 0;
}
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
int x = 0;
if (!isprime(a[i][j]))
x = *upper_bound(prr.begin(), prr.end(), a[i][j]);
else
x = a[i][j];
if (isprime(x)) {
v[i] += x - a[i][j];
h[j] += x - a[i][j];
}
}
int min = 1000000000;
for (int i = 0; i < n; i++)
if (v[i] < min) min = v[i];
for (int i = 0; i < m; i++)
if (h[i] < min) min = h[i];
cout << min;
cin >> min;
}
| CPP |
271_B. 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
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. | 2 | 8 | def sieve(n):
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
a,m = map(int,input().split())
no=100100
prime = [True for i in range(no+1)]
sieve(no)
prime[0]=False
prime[1]=False
req=[0]*no
for i in range(no-2,-1,-1):
if prime[i]:
req[i]=0
else:
req[i]=req[i+1]+1
mat=[]
for i in range(a):
b = list(map(int,input().split()))
mat.append(b)
#print(mat,req[:100],prime[:100])
ans=10000000000
for i in range(a):
temp=0
for j in range(m):
temp+=req[mat[i][j]]
ans=min(ans,temp)
for i in range(m):
temp=0
for j in range(a):
temp+=req[mat[j][i]]
ans = min(ans,temp)
print(ans)
| PYTHON3 |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
long long k, p, h, b[555][555], a[555555];
long long mid, n, o, r, l;
bool y, m[1000001];
void s(long long r) {
for (long long i = 2; i * i <= r; i++) {
if (m[i] == false) {
for (long long j = i * 2; j <= r; j += i) {
m[j] = true;
}
}
}
for (long long i = 2; i <= r; i++) {
if (m[i] == false) a[o++] = i;
}
}
int main() {
s(1000000);
p = o = h = 1e15;
cin >> n >> o;
for (long long i = 0; i < n; i++) {
for (int j = 0; j < o; j++) cin >> b[i][j];
}
for (long long i = 0; i < n; i++) {
k = 0;
long long u = 0;
for (long long j = 0; j < o; j++) {
r = 78450;
l = 0;
k = 1e15;
while (l <= r) {
mid = (l + r) / 2;
if (b[i][j] > a[mid]) {
l = mid + 1;
} else if (b[i][j] < a[mid]) {
k = min(k, a[mid] - b[i][j]);
r = mid - 1;
} else {
k = 0;
break;
}
}
u += k;
}
p = min(u, p);
}
for (long long j = 0; j < o; j++) {
k = 0;
long long u = 0;
for (long long i = 0; i < n; i++) {
r = 78450;
l = 0;
k = 1e15;
while (l <= r) {
mid = (l + r) / 2;
if (b[i][j] > a[mid]) {
l = mid + 1;
} else if (b[i][j] < a[mid]) {
k = min(k, a[mid] - b[i][j]);
r = mid - 1;
} else {
k = 0;
break;
}
}
u += k;
}
h = min(u, h);
}
cout << min(h, p);
}
| CPP |
271_B. 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
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. | 2 | 8 | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main {
static ArrayList<Integer> prime;
public static void sieve()
{
boolean[] isPrime = new boolean[(int)1e6];
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for(int i = 2;i<isPrime.length;i++)
{
if(isPrime[i])
{
for(int j = i<<1;j<isPrime.length;j+=i)
{
isPrime[j] = false;
}
}
}
prime = new ArrayList<Integer>();
for (int i = 2; i < isPrime.length; i++) {
if(isPrime[i])
prime.add(i);
}
}
public static int bs(int n)
{
int lo = 0,hi=prime.size();
int ans = 0;
while(lo<=hi)
{
int mid = lo + (hi-lo)/2;
int cur = prime.get(mid);
if(cur>=n)
{
hi = mid-1;
ans = cur;
}
else
{
lo = mid+1;
}
}
return ans!=0?ans:n;
}
public static void main(String[] args) throws Throwable
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++)
{
st = new StringTokenizer(br.readLine());
for (int j = 0; j < m; j++)
{
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
sieve();
int ans = Integer.MAX_VALUE;
for (int i = 0; i < n; i++)
{
int cur = 0;
for (int j = 0; j < m; j++)
{
int maxPrime = bs(arr[i][j]);
cur += maxPrime-arr[i][j];
}
ans = Math.min(ans,cur);
}
for (int i = 0; i < m; i++)
{
int cur = 0;
for (int j = 0; j < n; j++)
{
int maxPrime = bs(arr[j][i]);
cur += maxPrime-arr[j][i];
}
ans = Math.min(ans,cur);
}
System.out.println(ans);
}
} | JAVA |
271_B. 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
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. | 2 | 8 | import java.util.*;
import java.io.*;
public class B {
static int[] primes;
public static void genPrime(){
ArrayList<Integer> p = new ArrayList<>();
for(int i=2;i<=100000;i++){
boolean t = true;
for(int j=0;j<p.size();j++){
if(i%p.get(j)==0){
t = false;
break;
}
}
if(t)
p.add(i);
}
p.add(100003);
primes = new int[p.size()];
for(int i=0;i<p.size();i++)
primes[i] = p.get(i);
}
public static int calc(int x){
int index = Arrays.binarySearch(primes, x);
if(index>=0)
return 0;
else
return primes[-index-1]-x;
}
public static void main(String[] args){
genPrime();
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
int[][] matrix = new int[n][m];
int[][] cnt = new int[n][m];
int[] row = new int[n];
int[] col = new int[m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
matrix[i][j] = sc.nextInt();
cnt[i][j] = calc(matrix[i][j]);
row[i] += cnt[i][j];
col[j] += cnt[i][j];
}
}
sc.close();
int min = Integer.MAX_VALUE;
for(int i=0;i<n;i++){
min = Math.min(min, row[i]);
}
for(int i=0;i<m;i++){
min = Math.min(min, col[i]);
}
out.println(min);
out.flush();
}
}
| JAVA |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int N = 510;
const int M = 100100;
int prime[M + 10], a[N][N], b[N][N], n, m;
int main() {
prime[1] = 1;
for (int i = 2; i <= M; ++i)
if (prime[i] == 0)
for (int j = i + i; j <= M; j += i) prime[j] = 1;
cin >> n >> m;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j) cin >> a[i][j];
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j)
while (prime[a[i][j] + b[i][j]]) ++b[i][j];
int mn = 1 << 30;
for (int i = 1; i <= n; ++i) {
int s = 0;
for (int j = 1; j <= m; ++j) s += b[i][j];
mn = min(mn, s);
}
for (int j = 1; j <= m; ++j) {
int s = 0;
for (int i = 1; i <= n; ++i) s += b[i][j];
mn = min(mn, s);
}
cout << mn << '\n';
}
| CPP |
271_B. 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
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. | 2 | 8 | def main():
limit = 110000
nums = [0]*limit
for i in xrange(2,limit):
if not nums[i]:
for j in xrange(i+i,limit,i):
nums[j]=1
delta = 0
for i in range(limit-1,0,-1):
if not nums[i]:
delta = 0
else:
nums[i]=delta
delta+=1
nums[1] = 1
A = []
B = []
C = []
nsums = []
msums = []
n,m = [int(i) for i in raw_input().split()]
for i in xrange(n):
A.append([int(i) for i in raw_input().split()])
B.append([0]*m)
C.append([0]*m)
for i in xrange(n):
for j in xrange(m):
B[i][j] = nums[A[i][j]]
nsums.append(sum(B[i]))
BT = map(list, zip(*B))
for i in xrange(m):
msums.append(sum(BT[i]))
for i in xrange(n):
for j in xrange(m):
C[i][j] = nsums[i] + msums[j] - B[i][j]
print min(nsums + msums)
main() | PYTHON |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
template <typename T>
void _read(T& t);
template <typename T>
void _read(vector<T>& v);
template <typename T1, typename T2>
void _read(pair<T1, T2>& p);
template <typename T>
void _read(T& t) {
cin >> t;
}
template <typename T>
void _read(vector<T>& v) {
for (unsigned _i = 0; _i < v.size(); _i++) _read(v[_i]);
}
template <typename T1, typename T2>
void _read(pair<T1, T2>& p) {
_read(p.first);
_read(p.second);
}
void _masterread() {}
template <typename T, typename... V>
void _masterread(T& t, V&... v) {
_read(t);
_masterread(v...);
}
template <typename T>
void _print(T t);
template <typename T>
void _print(vector<T>& v);
template <typename T1, typename T2>
void _print(pair<T1, T2>& p);
template <typename T>
void _print(T t) {
cout << t;
}
template <typename T>
void _print(vector<T>& v) {
for (unsigned _i = 0; _i < v.size(); _i++)
_print(v[_i]), cout << (_i == v.size() - 1 ? "" : " ");
}
template <typename T1, typename T2>
void _print(pair<T1, T2>& p) {
_print(p.first);
cout << " ";
_print(p.second);
}
void _masterprint() { cout << '\n'; }
template <typename T, typename... V>
void _masterprint(T t, V... v) {
_print(t);
if (sizeof...(v)) cout << " ";
_masterprint(v...);
}
template <typename T>
void _debug(T t);
template <typename T1, typename T2>
void _debug(pair<T1, T2> p);
template <typename T>
void _debug(vector<T> v);
template <typename T>
void _debug(T t) {
cerr << t;
}
template <typename T1, typename T2>
void _debug(pair<T1, T2> p) {
cerr << "{";
_debug(p.first);
cerr << ", ";
_debug(p.second);
cerr << "}";
}
template <typename T>
void _debug(vector<T> v) {
cerr << "(";
for (unsigned _i = 0; _i < v.size(); _i++)
_debug(v[_i]), cerr << (_i == v.size() - 1 ? "" : ", ");
cerr << ")";
}
void _masterdebug() { cerr << "]\n"; }
template <typename T, typename... V>
void _masterdebug(T t, V... v) {
_debug(t);
if (sizeof...(v)) cerr << ", ";
_masterdebug(v...);
}
const long long M = 1e9 + 7;
vector<long long> P;
void find_primes(long long n) {
vector<bool> cnt(n + 1, 0);
for (long long i = 2; i <= n; i++) {
for (long long j = i + i; j <= n; j += i) cnt[j] = true;
}
for (long long i = 2; i <= n; i++)
if (!cnt[i]) P.push_back(i);
}
void solve() {
long long n, m;
_masterread(n, m);
vector<vector<long long>> arr(n, vector<long long>(m));
_masterread(arr);
vector<vector<long long>> need(n, vector<long long>(m));
for (long long i = 0; i < n; i++) {
for (long long j = 0; j < m; j++) {
auto bst = lower_bound(P.begin(), P.end(), arr[i][j]);
need[i][j] = *bst - arr[i][j];
}
}
vector<long long> rows(n), cols(m);
for (long long i = 0; i < n; i++) {
for (long long j = 0; j < m; j++) {
rows[i] += need[i][j];
cols[j] += need[i][j];
}
}
long long mn = LLONG_MAX;
for (long long i = 0; i < n; i++) {
for (long long j = 0; j < m; j++) {
mn = min(mn, rows[i]);
mn = min(mn, cols[j]);
}
}
_masterprint(mn);
}
signed main() {
find_primes(2e5);
cin.sync_with_stdio(false), cin.tie(nullptr);
solve();
}
| CPP |
271_B. 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
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. | 2 | 8 | import java.io.*;
import java.util.*;
public class B implements Runnable {
final int cnt = 200000;
private void Solution() throws IOException {
boolean[] prime = new boolean[2 * cnt + 1];
Arrays.fill(prime, true);
prime[0] = prime[1] = false;
for (int i = 2; i * i <= 2 * cnt; i++)
if (prime[i])
for (int j = i * i; j <= 2 * cnt; j += i)
prime[j] = false;
int[] res = new int[cnt + 1];
for (int i = 1; i <= cnt; i++)
for (int j = i; j <= 2 * cnt; j++)
if (prime[j]) {
res[i] = j;
break;
}
int n = nextInt(), m = nextInt();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = nextInt();
int min = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int cur = 0;
for (int j = 0; j < m; j++)
cur += res[a[i][j]] - a[i][j];
min = Math.min(min, cur);
}
for (int i = 0; i < m; i++) {
int cur = 0;
for (int j = 0; j < n; j++)
cur += res[a[j][i]] - a[j][i];
min = Math.min(min, cur);
}
System.out.println(min);
}
public static void main(String[] args) {
new B().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tokenizer;
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
Solution();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(261);
}
}
void halt() {
out.close();
System.exit(0);
}
void print(Object... obj) {
for (int i = 0; i < obj.length; i++) {
if (i != 0)
out.print(" ");
out.print(obj[i]);
}
}
void println(Object... obj) {
print(obj);
out.println();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
return in.readLine();
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(nextLine());
return tokenizer.nextToken();
}
}
| JAVA |
271_B. 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
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. | 2 | 8 | k=[0]*(200001)
primes=[]
for i in range(2,200001):
if k[i]==0:
primes.append(i)
for j in range(i,200001,i):k[j]=1
def bin(x):
lo,hi=0,len(primes)
ans=0
while lo<=hi:
mid = (hi+lo)//2
if primes[mid]==x:return 0
if primes[mid]<x:lo=mid+1
else:ans=mid;hi=mid-1
return primes[ans]-x
a,b=map(int,input().split())
r=[0]*a
c=[0]*b
for i in range(a):
gh=0
for u,v in enumerate(map(int,input().split())):
t=bin(v)
c[u]+=t
gh+=t
r[i]=gh
print(min(min(r),min(c))) | PYTHON3 |
271_B. 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
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. | 2 | 8 | def to_prime(n):
step = 0
i = n
while not is_prime[i]:
step += 1
i += 1
return step
R = 10 ** 5 + 300
is_prime = [0] * (R + 1)
is_prime[1] = 1
d = 2
while d * d <= R:
if not is_prime[d]:
for i in range(d ** 2, R + 1, d):
is_prime[i] = 1
d += 1
for i in range(R + 1):
if is_prime[i]:
k = i
step = 0
while k <= R and is_prime[k]:
k += 1
step += 1
is_prime[i] = step
n, m = map(int, input().split())
a = []
for i in range(n):
a.append(list(map(int,input().split())))
min_step = 10**5
for j in range(n):
step = 0
i = 0
while i < m:
if is_prime[a[j][i]] > 0:
step += is_prime[a[j][i]]
i += 1
if step < min_step:
min_step = step
for j in range(m):
step = 0
i = 0
while i < n:
if is_prime[a[i][j]] > 0:
step += is_prime[a[i][j]]
i += 1
if step < min_step:
min_step = step
print(min_step) | PYTHON3 |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int prime[200005];
void sieve() {
prime[0] = prime[1] = 1;
for (int i = 2; i < 200005; i += 1 + (1 & i)) {
if (!prime[i]) {
if (i <= 200005 / i)
for (int j = i * i; j < 200005; j += i) {
prime[j] = 1;
}
for (int j = i - 1; j >= 0 && prime[j]; j--) {
prime[j] = i;
}
}
}
}
int mat[504][504];
int main() {
sieve();
int n, m;
int Min = 1e9;
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> mat[i][j];
}
}
for (int i = 0; i < n; i++) {
int cnt1 = 0;
for (int j = 0; j < m; j++) {
int x1 = (prime[mat[i][j]] ? prime[mat[i][j]] - mat[i][j] : 0);
cnt1 += x1;
}
Min = min(Min, cnt1);
}
for (int i = 0; i < m; i++) {
int cnt1 = 0;
for (int j = 0; j < n; j++) {
int x1 = (prime[mat[j][i]] ? prime[mat[j][i]] - mat[j][i] : 0);
cnt1 += x1;
}
Min = min(Min, cnt1);
}
cout << Min << "\n";
}
| CPP |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
bool primes[100005];
int sol[100005];
void sieve() {
memset(primes, true, sizeof primes);
primes[0] = primes[1] = false;
int i, j;
for (i = 2; i * i <= 100005; i++) {
if (primes[i]) {
for (j = i * i; j < 100005; j += i) primes[j] = false;
}
}
int a = -1;
for (i = 100005; i >= 0; i--) {
if (primes[i]) a = i;
sol[i] = a;
}
}
int main() {
int n, m;
sieve();
cin >> n >> m;
int arr[n][m];
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
cin >> arr[i][j];
}
}
int arr1[500] = {0}, arr2[500] = {0};
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
int tmp = sol[arr[i][j]] - arr[i][j];
arr1[i] += tmp;
arr2[j] += tmp;
}
}
int mn = 100000000;
for (i = 0; i < n; i++) mn = min(mn, arr1[i]);
for (i = 0; i < m; i++) mn = min(mn, arr2[i]);
cout << mn;
return 0;
}
| CPP |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
bool compound[100030 + 1];
set<int> s;
unsigned long long int l, h;
int val, t;
void criba() {
for (int i = 2; i < 100030; i++) {
if (!compound[i]) {
s.insert(i);
val = i + i;
while (val <= 100030) {
compound[val] = true;
val += i;
}
}
}
}
int main() {
criba();
int h, w;
scanf("%d %d", &h, &w);
vector<vector<int>> m(h, vector<int>(w));
for (int i = 0; i < h; i++)
for (int j = 0; j < w; j++) scanf("%d", &m[i][j]);
compound[1] = 1;
compound[0] = 1;
vector<vector<int>> mf(h, vector<int>(w, 0));
for (int i = 0; i < h; i++)
for (int j = 0; j < w; j++) {
if (compound[m[i][j]]) mf[i][j] = *s.upper_bound(m[i][j]) - m[i][j];
}
vector<int> filas(h);
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
filas[i] += mf[i][j];
}
}
vector<int> columnas(w);
for (int j = 0; j < w; j++) {
for (int i = 0; i < h; i++) {
columnas[j] += mf[i][j];
}
}
int minfil = filas[0];
for (int i = 1; i < h; i++) minfil = min(minfil, filas[i]);
int mincol = columnas[0];
for (int i = 1; i < w; i++) mincol = min(mincol, columnas[i]);
cout << min(minfil, mincol) << endl;
return 0;
}
| CPP |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
vector<int> P;
char crivo[1000000];
int m[512][512];
int mm[512][512];
int N, M;
int main() {
int i, n, a;
memset(crivo, 0, sizeof(crivo));
for (i = 2; i < 1000000; i++) {
if (crivo[i]) continue;
P.push_back(i);
for (n = i + i; n < 1000000; n += i) crivo[n] = 1;
}
scanf("%d %d", &N, &M);
for (i = 0; i < N; i++)
for (n = 0; n < M; n++) {
scanf("%d", &a);
mm[i][n] = m[i][n] = *lower_bound(P.begin(), P.end(), a) - a;
if (n > 0) m[i][n] += m[i][n - 1];
if (i > 0) mm[i][n] += mm[i - 1][n];
}
int R = 0x3f3f3f3f;
for (i = 0; i < N; i++) {
R = min(R, m[i][M - 1]);
}
for (n = 0; n < M; n++) {
R = min(R, mm[N - 1][n]);
}
printf("%d\n", R);
return 0;
}
| CPP |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5, M = 6e2;
long long n, m, arr[M][M], cnt = 1e19, sum;
vector<long long> v;
bitset<N> isprime;
void sieve() {
isprime.set();
isprime[0] = isprime[1] = 0;
for (int i = 2; i <= N / i; i++) {
if (isprime[i]) {
for (int j = i * i; j < N; j += i) isprime[j] = 0;
}
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
sieve();
for (long long i = 2; i < N; i++)
if (isprime[i]) v.push_back(i);
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) cin >> arr[i][j];
for (int i = 0; i < n; i++) {
sum = 0;
for (int j = 0; j < m; j++) {
long long x = v[lower_bound(v.begin(), v.end(), arr[i][j]) - v.begin()];
sum += (x - arr[i][j]);
}
cnt = min(cnt, sum);
}
for (int i = 0; i < m; i++) {
sum = 0;
for (int j = 0; j < n; j++) {
long long x = v[lower_bound(v.begin(), v.end(), arr[j][i]) - v.begin()];
sum += (x - arr[j][i]);
}
cnt = min(cnt, sum);
}
cout << cnt;
return 0;
}
| CPP |
271_B. 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
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. | 2 | 8 | def I(): return(list(map(int,input().split())))
def sieve(n):
p=2
primes=[True]*(n+1)
primes[1]=False
primes[0]=False
while(p*p<=n):
if primes[p]:
# // Update all multiples of p greater than or
# // equal to the square of it
# // numbers which are multiple of p and are
# // less than p^2 are already been marked.
for i in range(p*p,n+1,p):
primes[i]=False
p+=1
return primes
n,m=I()
x=[]
primes=sieve(100000)
diffToNextPrime=[0]*(100001)
p=100003
for i in range(100000,-1,-1):
if primes[i]:
p=i
diffToNextPrime[i]=p-i
# print(p,i)
# print(diffToNextPrime[12049])
for i in range(n):
x.append(I())
m=len(x[0])
ma=99999999
for i in range(n):
s=0
for j in range(m):
# print(x[i][j])
x[i][j]=diffToNextPrime[x[i][j]]
s+=x[i][j]
# print(*x[i])
ma=min(s,ma)
for i in range(m):
s=0
for j in range(n):
# x[j][i]=diffToNextPrime[p]
s+=x[j][i]
ma=min(s,ma)
print(ma)
| PYTHON3 |
271_B. 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
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. | 2 | 8 | n=100100
p=[0,0]+[1]*(n)
p[0],p[1]=0,0
n1=int(n**0.5)
for i in range(2,n1):
if p[i]==1:
for j in range(i*i,n,i):
p[j]=0
for k in range(n,-1,-1):
if p[k]:
ind=k
p[k]=0
else:
p[k]=ind-k
lst=[]
x,y=map(int,input().split())
for j in range(x):
l=[]
for i in map(int,input().split()):
l.append(p[i])
lst.append(l)
st=[]
for x in lst:
st.append(sum(x))
for x in zip(*lst):
st.append(sum(x))
print(min(st)) | PYTHON3 |
271_B. 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
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. | 2 | 8 | import java.io.*;
import java.util.*;
public class Round166Div2 {
public static void main(String[] args) throws IOException {
rd = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
st = new StringTokenizer(rd.readLine());
int N = Integer.parseInt(st.nextToken()), M = Integer.parseInt(st.nextToken());
int[][] A = new int[N][M];
for(int i=0; i<N; i++){
st = new StringTokenizer(rd.readLine());
for(int j=0; j<M; j++){
A[i][j] = Integer.parseInt(st.nextToken());
}
}
for(int i=2; i<=150000; i++){
if(notPrime[i]!=0) continue;
for(int j=2; i*j<notPrime.length; j++){
notPrime[i*j]++;
}
}
int k = 0;
for(int i=2; i<notPrime.length; i++){
if(notPrime[i]==0){
primes[k] = i;
k++;
}
}
int[][] B = new int[N][M];
for(int i=0; i<N; i++){
for(int j=0; j<M; j++){
for(int t=0; ; t++){
if(notPrime[A[i][j]+t]==0 && A[i][j]+t>1){
B[i][j] = t;
break;
}
}
}
}
int min = Integer.MAX_VALUE;
for(int i=0; i<N; i++){
int s = 0;
for(int j=0; j<M; j++){
s += B[i][j];
}
min = Math.min(s, min);
}
for(int i=0; i<M; i++){
int s = 0;
for(int j=0; j<N; j++) s += B[j][i];
min = Math.min(min, s);
}
System.out.println(min);
}
static int[] primes = new int[200000];
static int[] notPrime = new int[200000];
static BufferedReader rd;
static PrintWriter pw;
static StringTokenizer st;
}
| JAVA |
271_B. 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
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. | 2 | 8 | def Sieve():
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * 2, n + 1, p):
prime[i] = False
p += 1
prime[0]= False
prime[1]= False
n = 10**5 + 12345
prime = [True for i in range(n + 1)]
Sieve()
n, m = [int(j) for j in input().split()]
M = []
for i in range(n):
r = [int(j) for j in input().split()]
for j in range(m):
t = r[j]
while(True):
if(prime[t]):
r[j] = t - r[j]
break
t += 1
M.append(r)
ans = 12345678901231234
for i in range(n):
if(ans > sum(M[i])):
ans = sum(M[i])
for j in range(m):
sum = 0
for i in range(n):
sum += M[i][j]
if (ans > sum):
ans = sum
print(ans)
| PYTHON3 |
271_B. 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
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. | 2 | 8 | def gen_prime(n):
num = [0 for i in range(n+1)]
num[2] = 1
num[3] = 1
for i in range(4, n+1):
isprime = True
for j in range(2, int(i**0.5)+1):
if num[j]:
if not i%j:
isprime = False
break
if isprime:
num[i] = 1
prime = []
for i in range(2, n+1):
if num[i]:
prime.append(i)
return prime
n, m = map(int, input().split())
prime = gen_prime(10**5+100)
def closest(x):
l = 0; r = len(prime)-1
while l < r:
mid = (l+r)//2
if prime[mid] == x:
return prime[mid]
elif prime[mid] > x:
r = mid
else:
l = mid+1
return prime[l]
a = [0 for i in range(n)]
for i in range(n):
a[i] = [int(i) for i in input().split()]
diff = [[0 for i in range(m)] for i in range(n)]
for i in range(n):
for j in range(m):
diff[i][j] = closest(a[i][j]) - a[i][j]
min_sum = (10**5)*m
for i in range(n):
temp = sum(diff[i])
if temp < min_sum:
min_sum = temp
total = min_sum
min_sum = (10**5)*n
for i in range(m):
temp = 0
for j in range(n):
temp += diff[j][i]
if temp < min_sum:
min_sum = temp
print(min(total,min_sum)) | PYTHON3 |
271_B. 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
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. | 2 | 8 | I = lambda :map(int , raw_input().split())
n , m = I()
a = [I() for _ in xrange(n)]
N = 110000
p = [0] * N
_next = [0] * N
for i in xrange(2 , N):
if not p[i]:
for j in range(i * i , N , i):
p[j] = 1
cur_cnt = N - 1
for i in xrange(N - 1 , 1 , -1):
if not p[i]:
cur_cnt = i
_next[i] = cur_cnt
_next[1] = 2
answer = 10**9
for i in a:
answer = min(answer , sum([_next[j] - j for j in i]))
for i in zip(*a):
answer = min(answer , sum([_next[j] - j for j in i]))
print answer
| PYTHON |
271_B. 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
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. | 2 | 8 | import time
primes = list()
def generate_primes():
a=[0]*100010
for x in range(2,100004):
if a[x]==0:
primes.append(x)
j=2
while j*x<100004:
a[j*x]=1
j+=1
def bin_search(x):
#if x < primes[0]: return -1
left = 0
right = len(primes)-1
while (right>left):
mid = (left+right)/2
if x == primes[mid]: return (mid,1)
if x>primes[mid]:
left=mid+1
else:
right=mid
return (left,0)
#print mid
n,m = map(int,raw_input().split())
mat = list()
for i in range(n):
mat.append(map(int,raw_input().split()))
start = time.time()
mas = generate_primes()
cols = list()
rows = list()
for i in range(n): cols.append(0)
for j in range(m): rows.append(0)
for i in range(n):
for j in range(m):
ind = bin_search(mat[i][j])
if ind[1]==1:
cols[i]+=0
rows[j]+=0
else:
cols[i]+=primes[ind[0]]-mat[i][j]
rows[j]+=primes[ind[0]]-mat[i][j]
ans = min(min(cols),min(rows))
print ans
finish = time.time()
#print (finish - start)
| PYTHON |
271_B. 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
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. | 2 | 8 | MaxN=110010
u=[0 for i in range(MaxN)]
u[0]=u[1]=1
for i in range(2,MaxN):
if u[i]:
continue
j=i*2
while j<MaxN:
u[j]=1
j+=i
i=MaxN-2
while i>0:
u[i]=u[i+1] if u[i] else i
i-=1
n,m=map(int,raw_input().split())
a=[map(int,raw_input().split()) for i in range(n)]
for i in range(n):
for j in range(m):
a[i][j]=u[a[i][j]]-a[i][j]
ans1=min(sum(a[i][j] for j in range(m)) for i in range(n))
ans2=min(sum(a[i][j] for i in range(n)) for j in range(m))
print min(ans1,ans2)
| PYTHON |
271_B. 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
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. | 2 | 8 | import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
//solution classes here
public class Code {
//main solution here
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
static long mod = 998244353;//(long)1e9+7
//static ArrayList<Integer> list[] = new ArrayList[(int)1e6+1];
//static int color[] = new int[(int)1e6+1];
//static int visit[] = new int[(int)1e5+1];
//static Deque<Integer> q = new ArrayDeque<>();
public static void main(String[] args) throws IOException {
int n = sc.nextInt();
int m = sc.nextInt();
int[][] a = new int[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
a[i][j]=sc.nextInt();
}
}
ArrayList<Integer> primes = new ArrayList<>();
int sieve[] = new int[100008];
for(int i=2;i<=100007;i++) {
if(sieve[i]==0) {
primes.add(i);
for (int j = 1; j * i <= 100007; j++) {
sieve[i * j] = 1;
}
}
}
int ls = primes.size();
long[] td= new long[n];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
long diff=0;
int lo=0,hi=ls-1;
while (lo<=hi) {
int mid=lo+(hi-lo)/2;
if(primes.get(mid)>=a[i][j]) {
hi=mid-1;
diff=primes.get(mid)-a[i][j];
}
else {
lo=mid+1;
}
}
td[i]+=diff;
}
}
long[] cd = new long[m];
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++) {
long diff=0;
int lo=0,hi=ls-1;
while (lo<=hi) {
int mid=lo+(hi-lo)/2;
if(primes.get(mid)>=a[j][i]) {
hi=mid-1;
diff=primes.get(mid)-a[j][i];
}
else {
lo=mid+1;
}
}
cd[i]+=diff;
}
}
Arrays.sort(cd);
Arrays.sort(td);
out.print(Math.min(td[0],cd[0]));
out.flush();
out.close();
}
//solution functions here
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader fileReader) {
br = new BufferedReader(fileReader);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
/* *****************************************************************************************************************************
* I'M NOT IN DANGER, I'M THE DANGER!!!
* *****************************************************************************************************************************
*/ | JAVA |
271_B. 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
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. | 2 | 8 | ncrivo = 1000000
crivo = [True for i in range(ncrivo)]
crivo[0] = crivo[1] = False
for i in range(2, ncrivo):
if crivo[i]:
for j in range(i * i, ncrivo, i):
crivo[j] = False
# lendo dados
n, m = map(int, input().split())
data = []
for i in range(n):
data.append(list(map(int, input().split())))
# frequencia
contador = [0 for i in range(200000)]
contador[100000] = 3
for i in range(99999, -1, -1):
if crivo[i]:
contador[i] = 0
# print contador[i]
else:
contador[i] = 1 + contador[i + 1]
resultado = 100000
for i in range(n):
soma = 0
for j in range(m):
soma += contador[data[i][j]]
resultado = min(resultado, soma)
for i in range(m):
soma = 0
for j in range(n):
soma += contador[data[j][i]]
# print soma
resultado = min(resultado, soma)
print(resultado) | PYTHON3 |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
void fast_in_out() {
std::ios_base::sync_with_stdio(NULL);
cin.tie(NULL);
cout.tie(NULL);
}
int dx[] = {0, 0, -1, 1, -1, 1, -1, 1, 0};
int dy[] = {-1, 1, 0, 0, -1, -1, 1, 1, 0};
int lx[] = {2, 2, -1, 1, -2, -2, -1, 1};
int ly[] = {-1, 1, 2, 2, 1, -1, -2, -2};
const long double eps = 1e-9;
const int N = 1e5 + 50, M = 1e5 + 10, mod = 1e9 + 7;
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
long long lcm(long long a, long long b) {
long long t = gcd(a, b);
return t ? (a / t * b) : 0;
}
bool prm[N];
vector<int> v;
int cost[N];
int adj[505][505];
long long row[505], col[505];
void sieve() {
v.push_back(2);
for (int i = 4; i < N; i += 2) prm[i] = 1;
for (int i = 3; i < N; i += 2)
if (!prm[i]) {
v.push_back(i);
for (int j = i + i; j < N; j += i) prm[j] = 1;
}
}
int main() {
fast_in_out();
sieve();
int n, m;
cin >> n >> m;
for (int i = 0, j = 0; i < M; i++) {
cost[i] = v[j] - i;
if (v[j] == i) ++j;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int x;
cin >> x;
x = cost[x];
row[i] += x;
col[j] += x;
}
}
long long ans = row[0];
for (int i = 0; i < n; i++) ans = min(ans, row[i]);
for (int j = 0; j < m; j++) ans = min(ans, col[j]);
cout << ans << '\n';
return 0;
}
| CPP |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
int a[501][501], p[100010];
int next(int n) {
int i;
for (i = n; p[i]; i++)
;
return i;
}
int main() {
int m, n, i, j, s, min = 10000000;
p[0] = p[1] = 1;
for (i = 2; i * i < 100010; i++)
if (p[i] == 0)
for (j = i * 2; j < 100010; j += i) p[j] = 1;
scanf("%d%d", &n, &m);
for (i = 0; i < n; i++)
for (j = 0; j < m; j++) {
scanf("%d", &a[i][j]);
a[i][j] = next(a[i][j]) - a[i][j];
a[n][j] += a[i][j];
a[i][m] += a[i][j];
}
for (i = 0; i < n; i++)
if (a[i][m] < min) min = a[i][m];
for (i = 0; i < m; i++)
if (a[n][i] < min) min = a[n][i];
printf("%d\n", min);
return 0;
}
| CPP |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
long long count(int n) {
if (n == 1)
return 0;
else if (n == 3)
return 8;
else
return count(n - 2) + (n * 4 - 4) * floor(n / 2.0);
}
bool isPrime(int n) {
int i, flag = 0;
if (n % 2 == 0)
flag = 1;
else {
for (i = 3; i <= sqrt(n); i += 2) {
if (n % i == 0) {
flag = 1;
break;
}
}
}
if (flag == 1)
return false;
else
return true;
}
int next_prime(int a) {
int i, j, flag;
for (i = a + 1;; i++) {
flag = 0;
if (i % 2 != 0) {
for (j = 3; j <= sqrt(i); j++) {
if (i % j == 0) flag = 1;
}
}
if (flag == 0 && i % 2 != 0) return i;
}
}
int main() {
long long t, tt, n, d, max, min, flag, c, l, k, i, j, m, x, start, end;
t = 1;
while (t--) {
cin >> n >> m;
int a[n][m];
vector<int> v;
max = -1;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
cin >> a[i][j];
if (a[i][j] > max) max = a[i][j];
}
}
start = -1;
tt = next_prime(max);
bool prime[tt + 1];
memset(prime, true, sizeof(prime));
for (int p = 2; p * p <= tt; p++) {
if (prime[p] == true) {
for (int i = p * 2; i <= tt; i += p) prime[i] = false;
}
}
for (i = 0; i < n; i++) {
c = 0;
for (j = 0; j < m; j++) {
if (a[i][j] == 1)
c = c + 1;
else if (prime[a[i][j]] == true)
c = c;
else {
for (k = a[i][j]; prime[k] == false; k++) {
}
c = c + k - a[i][j];
}
}
v.push_back(c);
}
for (j = 0; j < m; j++) {
c = 0;
for (i = 0; i < n; i++) {
if (a[i][j] == 1)
c = c + 1;
else if (prime[a[i][j]] == true)
c = c;
else {
for (k = a[i][j]; prime[k] == false; k++) {
}
c = c + k - a[i][j];
}
}
v.push_back(c);
}
sort(v.begin(), v.end());
cout << v[0] << endl;
}
}
| CPP |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
template <typename T, typename U>
static inline void amin(T &x, U y) {
if (y < x) x = y;
}
template <typename T, typename U>
static inline void amax(T &x, U y) {
if (x < y) x = y;
}
using namespace std;
const int N = 1e6;
int p[N];
void solve() {
long long int n, m, i, j, ans = INT_MAX;
cin >> n >> m;
int a[n][m];
for (i = 0; i < n; i++)
for (j = 0; j < m; j++) cin >> a[i][j];
fill(p, p + N, 1);
p[1] = 0;
for (i = 2; i * i <= N; i++) {
if (p[i]) {
for (j = i * i; j <= N; j += i) p[j] = 0;
}
}
set<int> s;
for (i = 1; i < N; i++)
if (p[i]) s.insert(i);
for (i = 0; i < n; i++) {
long long int sum = 0;
for (j = 0; j < m; j++) {
if (s.find(a[i][j]) == s.end()) {
auto n = *s.upper_bound(a[i][j]);
sum += n - a[i][j];
}
}
amin(ans, sum);
}
for (j = 0; j < m; j++) {
long long int sum = 0;
for (i = 0; i < n; i++) {
if (s.find(a[i][j]) == s.end()) {
auto n = *s.upper_bound(a[i][j]);
sum += n - a[i][j];
}
}
amin(ans, sum);
}
cout << ans << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t = 1;
while (t--) {
solve();
}
return 0;
}
| CPP |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
bool v[110001];
int n, m, i, p[100001], c, j, Next[100001], k, w[501][501], S, Res = 999999999;
int main() {
p[c++] = 2;
for (i = 3; i < 110000; i += 2) {
if (v[i]) continue;
p[c++] = i;
for (j = 3 * i; j < 110000; j += i << 1) {
v[j] = true;
}
}
k = 0;
for (i = 1; i <= 100000; i++) {
while (p[k] < i) k++;
Next[i] = p[k] - i;
}
scanf("%d%d", &n, &m);
for (i = 1; i <= n; i++) {
S = 0;
for (j = 1; j <= m; j++) {
scanf("%d", &w[i][j]);
S += Next[w[i][j]];
}
if (S < Res) Res = S;
}
for (i = 1; i <= m; i++) {
S = 0;
for (j = 1; j <= n; j++) {
S += Next[w[j][i]];
}
if (S < Res) Res = S;
}
printf("%d\n", Res);
}
| CPP |
271_B. 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
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. | 2 | 8 | def main():
entrada = input().split(" ")
valor1 = int(entrada[0])
valor2 = int(entrada[1])
num1 = 100025
num2 = 2
matriz = []
primos = [True]*num1
primos = set_numeros_nao_primos(num1, num2, primos)
for i in range(valor1):
linha = list(map(int,input().split()))
matriz.append(linha)
resposta = 100000
resposta = min(resposta, calcula_linha(resposta, valor1, valor2, matriz, num1, primos))
resposta = min(resposta, calcula_coluna(resposta, valor1, valor2, matriz, num1, primos))
print(resposta)
def calcula_linha(res, n, m, matriz, num1, primos):
for i in range(n):
movimentos = 0
for j in range(m):
result = matriz[i][j]
for k in range(result,num1):
if primos[k] == True:
movimentos += k-result
break
res = min(res, movimentos)
return res
def calcula_coluna(res, n, m, matriz, num1, primos):
for i in range(m):
movimentos = 0
for j in range(n):
result = matriz[j][i]
for k in range(result,num1):
if primos[k] == True:
movimentos += k-result
break
res = min(res, movimentos)
return res
def set_numeros_nao_primos(num1, num2, numerosPrimos):
for i in range(num2,num1):
j = i
while(j + i < num1):
j += i
numerosPrimos[j] = False
numerosPrimos[1] = False
numerosPrimos[0] = False
return numerosPrimos
if __name__ == "__main__":
main()
| PYTHON3 |
271_B. 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
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. | 2 | 8 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class BOOL {
private static FastReader in =new FastReader();
static ArrayList<Integer> A=new ArrayList();
static HashMap <Integer,Integer> Map =new HashMap();
static boolean B[][];
static int n,m,x,Z[][];
public static void main(String[] args) {
FindPrime(100090);
n=in.nextInt();m=in.nextInt();
Z=new int[n][m];
for(int i=0;i<n;i++){
for(int u=0;u<m;u++){
x=in.nextInt();
if(!Map.containsKey(x)){
is_P(x,i,u);}
}}
x=0;
int max=Integer.MAX_VALUE;
for(int i=0;i<n;i++){
for(int u=0;u<m;u++){
x+=Z[i][u];
}
if(max>x){max=x;}
x=0;
}
x=0;
for(int u=0;u<m;u++){
for(int i=0;i<n;i++){
x+=Z[i][u];
}
if(max>x){max=x;}
x=0;
}
System.out.println(max);
}
static void FindPrime(int o){
A.add(2);
Map.put(2, 0);
for(int i=3;i<o;i+=2)
{for(int u=0;u<=A.size();u++){
if(u==A.size()){A.add(i);Map.put(i, u);break;}
if(i%A.get(u)==0)break;
}}
}
static void is_P(int x,int n,int m){
if(Map.containsKey(x)){return;}
Z[n][m]++;
is_P(x+1,n,m);
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
| JAVA |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
bool isPrime(int x) {
if (x < 2) return false;
for (int i = 2; i <= sqrt(x); i++)
if (!(x % i)) return false;
return true;
}
int main() {
int nextPrime[100000];
for (int i = 0; i < 100000; i++) {
for (int j = i + 1;; j++)
if (isPrime(j)) {
nextPrime[i] = j;
break;
}
}
int n, m, row[500] = {}, col[500] = {};
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
int temp;
cin >> temp;
row[i] += nextPrime[temp - 1] - temp;
col[j] += nextPrime[temp - 1] - temp;
}
int min = row[0];
for (int i = 0; i < n; i++) min = (row[i] < min) ? row[i] : min;
for (int j = 0; j < m; j++) min = (col[j] < min) ? col[j] : min;
cout << min;
return 0;
}
| CPP |
271_B. 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
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. | 2 | 8 | import math
def prime(n):
ok= True
for i in range(2, int(math.sqrt(n))):
if(n%i==0):
ok = False
break
if(ok):
return True
else:
return False
def fact(a,b):
ans = 1
for i in range(a, b+1):
ans*= i
return str(ans)-1
def comb(n, c):
return fact(n)//(fact(n-c)*c)
def primesieve(x):
nos = [1 for i in range(x+1)]
nos[0], nos[1] = 0,0
p = 2
while(p <= x):
if(nos[p]):
for i in range(p*2, x+1, p):
nos[i] = 0
p+=1
ans = []
for i in range(x+1):
if(nos[i]):
ans.append(i)
return ans
def srh(grid, x):
left = 0
right = len(grid)
while(left < right):
mid = (left+right)//2
if(grid[mid] > x):
right = mid
else:
left = mid+1
if(grid[left-1]==x):
return grid[left-1]
if(left==len(grid)):
return grid[left-1]
return grid[left]
ps = primesieve(100200)
n,m = map(int, input().split())
grid = []
for i in range(n):
grid.append(list(map(int, input().split())))
ptgrid = [[0 for i in range(m)]for i in range(n)]
for f in range(n):
for s in range(m):
ptgrid[f][s] = srh(ps, grid[f][s])-grid[f][s]
ans = int(10e5)
for s in range(m):
tans = 0
for f in range(n):
tans+=ptgrid[f][s]
ans = min(ans, tans)
for i in range(n):
ans = min(ans, sum(ptgrid[i]))
print(ans)
| PYTHON3 |
271_B. 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
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. | 2 | 8 | num1= 102001
num2= 2
prime=[1]*num1
prime[1]=0
prime[0]=0
for i in range(num2,num1):
j=i
while(j+i<num1):
j+=i
prime[j]=0
l=[]
n,m=map(int,input().split())
for i in range(n):
t=list(map(int,input().split()))
l.append(t)
ans=100000
for i in range(n):
tot=0
for j in range(m):
result=l[i][j]
for k in range(result,num1):
if prime[k]==1:
tot+=k-result
break
ans=min(ans,tot)
for j in range(m):
tot=0
for i in range(n):
result=l[i][j]
for k in range(result,num1):
if prime[k]==1:
tot+=k-result
break
ans=min(ans,tot)
print(ans)
| PYTHON3 |
271_B. 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
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. | 2 | 8 | import java.util.*;
import java.io.*;
public class palin {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
boolean prime[] = new boolean[100004];
for (int i = 2; i < 50003; i++) {
for (int j = 2; i * j < 100004; j++) {
prime[(i * j) - 1] = true;
}
}
prime[0] = true;
prime[1] = false;
int r = scan.nextInt(), c = scan.nextInt(), sum = 0, sum2 = 0, min = Integer.MAX_VALUE, x;
int[][] a = new int[r][c];
for (int i = 0; i < r; i++) {
sum = 0;
for (int j = 0; j < c; j++) {
x = scan.nextInt();
while (prime[x - 1]) {
sum++;
x++;
a[i][j]++;
}
}
min = Math.min(min, sum);
}
for (int i = 0; i < c; i++) {
sum2 = 0;
for (int j = 0; j < r; j++) {
sum2 += a[j][i];
}
min = Math.min(min, sum2);
}
System.out.println(min);
}
} | JAVA |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int N = 1000001;
bool crib[N];
void criba() {
memset(crib, true, sizeof(crib));
crib[1] = false;
for (int i = 2; i <= N / 2; i++) {
if (crib[i] == true) {
for (int j = 2 * i; j <= N; j += i) {
crib[j] = false;
}
}
}
}
int mov_fila(int A[500][500], int i, int m) {
int sum = 0;
for (int j = 0; j < m; j++) {
if (crib[A[i][j]] == false) {
for (int k = A[i][j] + 1; k <= N; k++) {
if (crib[k]) {
sum += k - A[i][j];
break;
}
}
}
}
return sum;
}
int mov_columna(int A[][500], int j, int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
if (crib[A[i][j]] == false) {
for (int k = A[i][j] + 1; k <= N; k++) {
if (crib[k]) {
sum += k - A[i][j];
break;
}
}
}
}
return sum;
}
int main() {
int n, m;
cin >> n;
cin >> m;
int A[n][500];
criba();
int min;
bool termina = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> A[i][j];
}
if (i == 0) {
min = mov_fila(A, i, m);
} else {
if (mov_fila(A, i, m) < min) min = mov_fila(A, i, m);
}
if (min == 0) {
cout << "0";
termina = true;
break;
}
}
if (!termina) {
for (int j = 0; j < m; j++) {
if (mov_columna(A, j, n) < min) min = mov_columna(A, j, n);
if (min == 0) {
cout << "0";
termina = true;
break;
}
}
}
if (!termina) cout << min;
return 0;
}
| CPP |
271_B. 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
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. | 2 | 8 | import java.util.LinkedList;
import java.util.Scanner;
public class Contest_5C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] input1 = sc.nextLine().split(" ");
int rows = Integer.parseInt(input1[0]);
int cols = Integer.parseInt(input1[1]);
String[][] input2 = new String[rows][cols];
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows; i++) {
input2[i] = sc.nextLine().split(" ");
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = Integer.parseInt(input2[i][j]);
}
}
//Encontrar primos
boolean[] bools = new boolean[100000];
bools = calculaPrimos(100000);
LinkedList<Integer> aux = new LinkedList<>();
for ( int i = 1; i < bools.length; i++ ) {
if (bools[i] == true) {
aux.add(i);
}
}
int[] primos = new int[aux.size()+1];
for (int i = 0; i < primos.length-1; i++) {
primos[i] = aux.getFirst();
aux.removeFirst();
}
primos[primos.length-1] = 100003;
//Programa
int min = 0;
int cont = 0;
int index;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if(matrix[i][j] == 1) {
cont += 1;
}else {
index = binarySearch(matrix[i][j], primos);
cont += primos[index]-matrix[i][j];
}
}
if(i == 0) {
min = cont;
} else {
min = Math.min(min, cont);
}
cont = 0;
}
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
if(matrix[j][i] == 1) {
cont += 1;
} else {
index = binarySearch(matrix[j][i], primos);
cont += primos[index]-matrix[j][i];
}
}
min = Math.min(min, cont);
cont = 0;
}
System.out.println(min);
}
private static boolean[] calculaPrimos(int size) {
boolean arreglo[];
arreglo = new boolean[size + 1];
for (int i = 2; i < size; i++ ) {
arreglo[i] = true;
}
for ( int j = 2; j <= size; j++ ) {
if (arreglo[j] == true) {
for ( int k = 2; k <= (size)/j; k++ )
arreglo[k*j] = false;
}
}
return arreglo;
}
public static int binarySearch(int valor, int[] datos) {
int min = 0,
max = datos.length-1,
avg;
while(min <= max) {
avg = (min+max)/2;
if(valor > datos[avg] && valor < datos[avg+1]) {
avg++;
return avg;
} else if(valor < datos[avg]) {
max = avg-1;
} else if(valor > datos[avg]) {
min = avg+1;
} else {
return avg;
}
}
return -1;
}
}
| JAVA |
271_B. 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
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. | 2 | 8 | # JOAO MARCELO - 2021
# 271B
import math
from bisect import bisect_left
maxi = 100010
n, m = [int(x) for x in input().split()]
tag = [0] * maxi
lines = [0] * n
cols = [0] * m
prime = [0] * maxi
tag[0] = tag[1] = 1
count = 0
for i in range(2, maxi):
if(not tag[i]):
prime[count] = i
count += 1
j = 0
while(j < count and prime[j] * i < maxi):
tag[i * prime[j]] = 1
if(i % prime[j] == 0):
break
j += 1
matrix = []
prime = prime[0:count]
# print(prime)
for i in range(n):
col = [int(x) for x in input().split()]
matrix.append(col)
for l in range(n):
for c in range(m):
x = matrix[l][c]
if(tag[x]):
t = bisect_left(prime, x)
lines[l] += (prime[t] - x)
cols[c] += (prime[t] - x)
min_col = min(cols)
min_line = min(lines)
print(min(min_col, min_line))
| PYTHON3 |
271_B. 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
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. | 2 | 8 | import java.util.NavigableSet;
import java.util.Scanner;
import java.util.TreeSet;
public class B271 {
static NavigableSet<Integer> primes = new TreeSet<>();
static void initPrimes(int MAXN) {
int sqrtN = (int)Math.sqrt(MAXN);
boolean[] composite = new boolean[MAXN];
composite[0] = composite[1] = true;
for (int p=2; p<=sqrtN; p++) {
if (!composite[p]) {
for (int x=2*p; x<MAXN; x+=p) {
composite[x] = true;
}
}
}
for (int p=2; p<MAXN; p++) {
if (!composite[p]) {
primes.add(p);
}
}
}
public static void main(String[] args) {
initPrimes(100004);
Scanner in = new Scanner(System.in);
int R = in.nextInt();
int C = in.nextInt();
int[][] A = new int[R][C];
int min = Integer.MAX_VALUE;
for (int r=0; r<R; r++) {
int sum = 0;
for (int c=0; c<C; c++) {
int a = in.nextInt();
int value = primes.ceiling(a) - a;
A[r][c] = value;
sum += value;
}
min = Math.min(min, sum);
}
for (int c=0; c<C; c++) {
int sum = 0;
for (int r=0; r<R; r++) {
sum += A[r][c];
}
min = Math.min(min, sum);
}
System.out.println(min);
}
}
| JAVA |
271_B. 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
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. | 2 | 8 |
import java.util.*;
public class B271 {
public static boolean[] getListOfPrimalNumber() {
int n = 100004;
boolean[] arr = new boolean[n];
for (int p = 2; p < n; p++) arr[p] = true;
for (int p = 2; p < n; p++)
if (arr[p]) {
for (int j = 2 * p; j < n; j += p)
arr[j] = false;
}
return arr;
}
private static boolean isPrimal(int value) {
for (int i = 2; i < Math.sqrt(value); i++) {
if (value % i == 0) {
return true;
}
}
return false;
}
private static int getLessAmountStepToPrimal(int value, boolean[] list) {
for (int i = 0; value + i < list.length; i++) {
if (list[value + i]) {
return i;
}
}
return 0;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); //ΡΡΡΠΎΠΊΠΈ
int m = sc.nextInt(); //ΡΡΠΎΠ»Π±ΡΡ
boolean[] primal = getListOfPrimalNumber();
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = sc.nextInt();
}
}
int min = Integer.MAX_VALUE;
int current;
for (int i = 0; i < n; i++) {
current = 0;
for (int j = 0; j < m; j++) {
current += getLessAmountStepToPrimal(arr[i][j], primal);
}
if (current < min) {
min = current;
}
}
for (int i = 0; i < m; i++) {
current = 0;
for (int j = 0; j < n; j++) {
current += getLessAmountStepToPrimal(arr[j][i], primal);
}
if (current < min) {
min = current;
}
}
System.out.println(min);
}
}
| JAVA |
271_B. 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
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. | 2 | 8 | m = 1000000
p=2
d = [-1]*(m)
while p**2<=m:
if d[p]==-1:
for i in range(p*2, m , p):
d[i]=0
p+=1
d[0]=0
d[1]=0
w=[]
#print(d[:10])
g=0
for j in range(m-1,1,-1):
if d[j]!= -1:
w.append(g)
else:
g=j
w.append(g)
w.append(2)
w.append(2)
sq=w[::-1]
#print(sq)
n,m = map(int,input().split())
t=[]
f=[]
for i in range(n):
s=list(map(int,input().split()))
t.append(s)
for i in range(m):
h=[]
for j in range(n):
h.append(t[j][i])
f.append(h)
#print(sq[:10])
ans =999999999
for i in range(n):
u=0
for j in range(m):
u+=sq[t[i][j]]-t[i][j]
#print(u,t[i])
ans= min(u,ans)
for i in range(m):
u=0
for j in range(n):
u+=sq[f[i][j]]-f[i][j]
#print(f[i])
ans= min(u,ans)
print(ans)
| PYTHON3 |
271_B. 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
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. | 2 | 8 | import math
import sys
def get_primes_distances(limit):
distances = [0] * (limit +1)
sieve = [True] * (limit + 1)
sieve[0] = False
sieve[1] = False
i = 2
while (i * i <= limit):
if (sieve[i] == True):
for j in range(i * 2, (limit+1), i):
sieve[j] = False
i += 1
distances[100000] = 3
for i in range(99999, -1, -1):
if not sieve[i]:
distances[i] = distances[i+1]+1
return distances
distances = get_primes_distances(100000)
input = sys.stdin
[n, m]= list(map (int, input.readline().strip().split()))
matrix = []
min_result = ((10**5))
for i in range(n):
matrix.append(list(map (int, input.readline().strip().split())))
rows = [0]*n
columns = [0]*m
for i in range(n):
for j in range(m):
gap = distances[matrix[i][j]]
rows[i] += gap
columns[j] += gap
rows_min = min(rows)
rows_column = min(columns)
print(min(rows_min, rows_column))
| PYTHON3 |
271_B. 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
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. | 2 | 8 | def arr_inp(n):
if n == 1:
return [int(x) for x in stdin.readline().split()]
elif n == 2:
return [float(x) for x in stdin.readline().split()]
else:
return [str(x) for x in stdin.readline().split()]
def count_prime(n):
prim = defaultdict(lambda: 1, {i: 1 for i in range(n + 1)})
prim[0] = prim[1] = 0
i = 2
while (i * i <= n):
if prim[i]:
for j in range(i * 2, n + 1, i):
prim[j] = 0
i += 1
return list(filter(lambda x: prim[x], prim.keys()))
from sys import stdin
from collections import *
from bisect import *
n, m = arr_inp(1)
mat, primes, ans, col = [arr_inp(1) for i in range(n)], count_prime(100003), float('inf'), defaultdict(int)
for i in range(n):
r = 0
for j in range(m):
ix = bisect_right(primes, mat[i][j])
if primes[ix - 1] == mat[i][j]:
ix -= 1
col[j] += primes[ix] - mat[i][j]
r += primes[ix] - mat[i][j]
if i == n - 1:
ans = min(ans, col[j])
ans = min(ans, r)
print(ans)
| PYTHON3 |
271_B. 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
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. | 2 | 8 |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class B {
private static final String Object = null;
static BufferedReader in;
static StringTokenizer st;
static PrintWriter out;
public static void main(String[] args) throws IOException {
begin();
solve();
end();
}
private static void end() {
out.close();
}
private static void solve() throws IOException {
int n = nextInt();
int m = nextInt();
int [][] a = new int [n+1][m+1];
boolean []d1 = new boolean [n+1];
boolean []d2 = new boolean [m+1];
for (int i = 1; i <=n; i++) {
for (int j = 1; j <=m; j++) {
a[i][j] = nextInt();
boolean d = isprime(a[i][j]);
if (!d1[i]){
d1[i] = d;
}
if (!d2[j]){
d2[j] = d;
}
}
}
for (int i = 1; i <= n; i++) {
if (!d1[i]){
// System.out.println(i+" ");
System.out.println(0);
return;
}
}
for (int i = 1; i <= m; i++) {
if (!d2[i]){
System.out.println(0);
return;
}
}
int [][]cnt = new int [n+1][m+1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cnt[i][j] = 0;
while (isprime(a[i][j]+cnt[i][j])){
cnt[i][j]++;
}
}
}
int []dp1 = new int [n+1];
int []dp2 = new int [m+1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
// System.out.print(cnt[i][j]+" ");
dp1[i] += cnt[i][j];
dp2[j] += cnt[i][j];
}
// System.out.println();
}
int min = Integer.MAX_VALUE;
for (int i = 1; i <=n; i++) {
min = Math.min(min, dp1[i]);
}
for (int i = 1; i <=m; i++) {
min = Math.min(min, dp2[i]);
}
System.out.println(min);
}
private static boolean isprime(int n) {
if (n == 1) return true;
for (int i = 2; i*i <= n; i++) {
if (n%i == 0) return true;
}
return false;
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static void writeln(Object t) {
out.println(t);
}
private static void write(Object t) {
out.print(t);
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static String next() throws IOException {
while (!st.hasMoreElements())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
private static void begin() {
out = new PrintWriter(new OutputStreamWriter(System.out));
st = new StringTokenizer("");
in = new BufferedReader(new InputStreamReader(System.in));
}
}
| JAVA |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int N = 1000000;
int prime[N], primes[N];
void sieve() {
for (int i = 2; i <= N; i++) prime[i] = 1;
for (int i = 2; i * i <= N; i++)
if (prime[i])
for (int y = i * i; y <= N; y += i) prime[y] = 0;
}
int main() {
sieve();
int idx = 0;
for (int i = 0; i < N; i++) {
if (prime[i]) primes[idx++] = i;
}
int n, m, arr[501][501];
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++) {
for (int y = 0; y < m; y++) {
scanf("%d", &arr[i][y]);
if (prime[arr[i][y]])
arr[i][y] = 0;
else {
int *ptr = upper_bound(primes, primes + idx, arr[i][y]);
arr[i][y] = *ptr - arr[i][y];
}
}
}
int mn[2];
mn[0] = mn[1] = 1e6;
for (int i = 0; i < n; i++) {
int sum = 0;
for (int y = 0; y < m; y++) {
sum += arr[i][y];
}
mn[0] = min(mn[0], sum);
}
for (int i = 0; i < m; i++) {
int sum = 0;
for (int y = 0; y < n; y++) {
sum += arr[y][i];
}
mn[1] = min(mn[1], sum);
}
printf("%d\n", min(mn[0], mn[1]));
return 0;
}
| CPP |
271_B. 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
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. | 2 | 8 | def buil_prime_dict(n):
a =[x for x in range(n+1)]
a[1] = 0
lst = []
i = 2
while i <= n:
if a[i] != 0:
lst.append(a[i])
for j in range(i, n+1, i):
a[j] = 0
i += 1
return lst
prime_dict=buil_prime_dict(10**5+100)
def diff_search_number_prime(a,dictionary):
start_ind=0
stop_ind=len(dictionary)-1
if a == 1:
return 1
while (stop_ind-start_ind)!=1:
middle_ind=(stop_ind-start_ind)//2+start_ind
if a==dictionary[middle_ind] or a==dictionary[start_ind] or a==dictionary[stop_ind]:
return 0
elif a>dictionary[middle_ind]:
start_ind=middle_ind
else:
stop_ind=middle_ind
return abs(a-dictionary[stop_ind])
line1=input()
n=int(line1.split(' ')[0])
m=int(line1.split(' ')[1])
matrix=[]
max_num=0
for j in range(n):
line2=input()
d=[int(x) for x in line2.split(' ')]
matrix.append(d)
if max_num<max(d):
max_num=max(d)
dict_dist=[0,1]
for i in range(2,max_num+1):
dict_dist.append(diff_search_number_prime(i,prime_dict))
matrix=[[dict_dist[y] for y in i]for i in matrix]
results=[]
for x in matrix:
results.append(sum(x))
for x in zip(*matrix):
results.append(sum(x))
print(min(results))
| PYTHON3 |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
;
long long n, m;
cin >> n >> m;
long long mat[n][m];
for (long long i = 0; i < (long long)n; i++) {
for (long long j = 0; j < (long long)m; j++) {
cin >> mat[i][j];
}
}
vector<long long> primes;
long long a = 1, b = 100500;
if (a == 1) {
a++;
if (b >= 2) {
primes.push_back(a);
a++;
}
}
if (a == 2) primes.push_back(a);
if (a % 2 == 0) a++;
for (long long i = a; i <= b; i = i + 2) {
bool flag = 1;
for (long long j = 2; j * j <= i; ++j) {
if (i % j == 0) {
flag = 0;
break;
}
}
if (flag == 1) primes.push_back(i);
}
long long cnt = 0;
long long mx = LLONG_MAX;
for (long long i = 0; i < (long long)n; i++) {
long long cnt = 0;
for (long long j = 0; j < (long long)m; j++) {
auto it = lower_bound(primes.begin(), primes.end(), mat[i][j]);
if (*it != mat[i][j]) {
long long fis = *it - mat[i][j];
cnt += fis;
}
}
mx = min(cnt, mx);
}
for (long long i = 0; i < (long long)m; i++) {
long long cnt = 0;
for (long long j = 0; j < (long long)n; j++) {
auto it = lower_bound(primes.begin(), primes.end(), mat[j][i]);
if (*it != mat[j][i]) {
long long fis = *it - mat[j][i];
cnt += fis;
}
}
mx = min(mx, cnt);
}
cout << mx << "\n";
return 0;
}
| CPP |
271_B. 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
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. | 2 | 8 | import java.util.Scanner;
public class P271B
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[][] matrix = new int[n][m];
boolean[] primes = Eratesten(100003);
// int arrayMax = 1;
// int index = 0;
for (int i=0; i<n; i++)
for (int j=0; j<m; j++)
{
int temp = in.nextInt();
int temp2 = temp;
while (primes[temp])
{
temp++;
}
matrix[i][j] = temp - temp2;
//in.reset();
}
int min = Integer.MAX_VALUE;
for (int i=0; i<n; i++)
{
int sum = 0;
for (int j=0; j<m; j++)
sum += matrix[i][j];
min = Math.min(min, sum);
}
for (int i=0; i<m; i++)
{
int sum = 0;
for (int j=0; j<n; j++)
sum += matrix[j][i];
min = Math.min(min, sum);
}
System.out.println(min);
}
public static boolean[] Eratesten(int last) {
boolean[] numbers = new boolean[last + 1];
numbers[0] = true;
numbers[1] = true;
// int counter = 1;
loop: for (int i=3; i<=last; i++)
{
if (!numbers[i])
{
int t = (int) Math.sqrt(i);
for (int j=2; j<=t; j++)
{
if (i%j == 0)
{
int l = last/i;
for (int k=1; k<=l; k++)
{
numbers[k*i] = true;
}
continue loop;
}
}
// counter ++;
}
}
// int[] answer = new int[counter];
// int index = 0;
// for (int i=2; i<=last; i++)
// if (!numbers[i]) answer[index++] = i;
return numbers;
}
}
| JAVA |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
int n, m;
int ers[101000];
int mp[101000];
int a[510][510];
int ans;
int main() {
int i, j, tmp;
ers[0] = 1;
ers[1] = 1;
for (i = 2; i < 100100; i++) {
if (ers[i] == 0) {
for (j = i * 2; j < 100100; j += i) {
ers[j] = 1;
}
}
}
j = 999999;
for (i = 100100; i >= 0; i--) {
if (ers[i] == 0) j = i;
mp[i] = j - i;
}
scanf("%d%d", &n, &m);
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
scanf("%d", &a[i][j]);
}
}
ans = 999999999;
for (i = 0; i < n; i++) {
tmp = 0;
for (j = 0; j < m; j++) {
tmp += mp[a[i][j]];
}
if (tmp < ans) ans = tmp;
}
for (i = 0; i < m; i++) {
tmp = 0;
for (j = 0; j < n; j++) {
tmp += mp[a[j][i]];
}
if (tmp < ans) ans = tmp;
}
printf("%d", ans);
}
| CPP |
271_B. 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
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. | 2 | 8 | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
/**
* Works good for CF
*
* @author cykeltillsalu
*/
public class A {
// some local config
static boolean test = false;
static String testDataFile = "testdata.txt";
static String feedFile = "feed.txt";
CompetitionType type = CompetitionType.CF;
private static String ENDL = "\n";
private boolean[] siev(int n) {
boolean[] prime = new boolean[n+1];
Arrays.fill(prime, true);
prime[0] = false;
prime[1] = false;
for (int i = 2; i < prime.length; i++) {
int nr = i;
if(prime[nr]){
nr += i;
while(nr <= n){
prime[nr] = false;
nr += i;
}
}
}
return prime;
}
// solution
private void solve() throws Throwable {
int n = iread(), m = iread();
int[][] r = new int[n][m];
boolean[] isprime = siev(100500);
for (int i = 0; i < n; i++) {
out:for (int j = 0; j < m; j++) {
int c = iread();
int p = getPrime(isprime, c);
r[i][j] = p - c;
}
}
int best = Integer.MAX_VALUE/2;
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = 0; j < m; j++) {
sum += r[i][j];
}
best = Math.min(sum, best);
}
for (int i = 0; i < m; i++) {
int sum = 0;
for (int j = 0; j < n; j++) {
sum += r[j][i];
}
best = Math.min(sum, best);
}
System.out.println(best);
}
int[] val = new int[100001];
private int getPrime(boolean[] isprime, int c) {
if(val[c] > 0){
return val[c];
}
for (int i = c; ; i++) {
if(isprime[i]){
val[c] = i;
return i;
}
}
}
public int iread() throws Exception {
return Integer.parseInt(wread());
}
public double dread() throws Exception {
return Double.parseDouble(wread());
}
public long lread() throws Exception {
return Long.parseLong(wread());
}
public String wread() throws IOException {
StringBuilder b = new StringBuilder();
int c;
c = in.read();
while (c >= 0 && c <= ' ')
c = in.read();
if (c < 0)
return "";
while (c > ' ') {
b.append((char) c);
c = in.read();
}
return b.toString();
}
public static void main(String[] args) throws Throwable {
if (test) { // run all cases from testfile:
BufferedReader testdataReader = new BufferedReader(new FileReader(testDataFile));
String readLine = testdataReader.readLine();
int casenr = 0;
out: while (true) {
BufferedWriter w = new BufferedWriter(new FileWriter(feedFile));
if (!readLine.equalsIgnoreCase("input")) {
break;
}
while (true) {
readLine = testdataReader.readLine();
if (readLine.equalsIgnoreCase("output")) {
break;
}
w.write(readLine + "\n");
}
w.close();
System.out.println("Answer on case " + (++casenr) + ": ");
new A().solve();
System.out.println("Expected answer: ");
while (true) {
readLine = testdataReader.readLine();
if (readLine == null) {
break out;
}
if (readLine.equalsIgnoreCase("input")) {
break;
}
System.out.println(readLine);
}
System.out.println("----------------");
}
testdataReader.close();
} else { // run on server
new A().solve();
}
out.close();
}
public A() throws Throwable {
if (test) {
in = new BufferedReader(new FileReader(new File(feedFile)));
}
}
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(inp);
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
enum CompetitionType {
CF, OTHER
};
} | JAVA |
271_B. 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
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. | 2 | 8 | def _min(x, y):
if x < y:
return x
if y <= x:
return y
n = 100100
prime = [True for i in range(n+1)]
prime[0], prime[1] = False, False
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
n = 100100
nextPrime = [0 for _ in range(n+1)]
currentPrime = -1
for i in range(n, -1, -1):
if prime[i]:
nextPrime[i] = i
currentPrime = i
elif currentPrime == -1:
nextPrime[i] = -1
else:
nextPrime[i] = currentPrime
n, m = map(int, input().split())
rows = [0 for i in range(n)]
cols = [0 for i in range(m)]
for r in range(n):
row = [int(x) for x in input().split()]
for c in range(m):
x = row[c]
if not prime[x]:
x = nextPrime[x]
# while(not prime[x]):
# x+=1
rows[r] += (x - row[c])
cols[c] += (x - row[c])
min_row=min(rows)
min_cols=min(cols)
print(_min(min_row, min_cols)) | PYTHON3 |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-6;
const int PRECISION = 20;
const int MOD = 1e9 + 7;
struct node {
long long val;
vector<long long> formula;
node() { val = -1; }
};
struct group {
long long mul, last, gcd;
group(long long m, long long l, long long lm) {
mul = m;
last = l;
gcd = lm;
}
};
bool comp(pair<int, int> p1, pair<int, int> p2) {
return p1.second < p2.second;
}
int bs(vector<int> vc, int target) {
int low = 0, high = vc.size() - 1;
while (high > low) {
int mid = ((high - low + 1) / 2) + low;
if (vc[mid] <= target)
low = mid;
else
high = mid - 1;
}
return low;
}
long long gcd(long long a, long long b) {
if (a == 0) return b;
return gcd(b % a, a);
}
long long fastPow(long long a, long long n) {
if (n == 0) return 1;
if (n == 1) return a;
long long x = fastPow(a, n / 2);
x = (x * x);
return (n % 2 == 0 ? x : (x * a));
}
int char2index(char a) { return a >= 'a' ? a - 'a' : a - 'A' + 26; }
int flipCase(char a) {
return a >= 'a' ? char2index(a - ('a' - 'A')) : char2index(a + ('a' - 'A'));
}
void prefix(vector<long long> &arr) {
for (int i = 1; i < arr.size(); i++) arr[i] += arr[i - 1];
}
long long eval(vector<long long> &coeffs, long long x) {
long long ans = 0;
long long xs = 1;
for (long long i = coeffs.size() - 1; i >= 0; i--) {
ans += (coeffs[i] * xs);
xs *= x;
}
return ans;
}
int bracketToInt(char a) {
switch (a) {
case '(':
return 1;
case ')':
return -1;
case '{':
return 2;
case '}':
return -2;
case '[':
return 3;
case ']':
return -3;
case '<':
return 4;
case '>':
return -4;
default:
return -1;
}
}
long long findOpposite(long long x, long long y, long long n) {
long long ans = 0;
if (x - 2 >= 1) {
if (y - 1 >= 1) ans++;
if (y + 1 < n) ans++;
}
if (x + 2 <= n) {
if (y - 1 >= 1) ans++;
if (y + 1 <= n) ans++;
}
if (y - 2 >= 1) {
if (x + 1 <= n) ans++;
if (x - 1 >= 1) ans++;
}
if (y + 2 < n) {
if (x + 1 <= n) ans++;
if (x - 1 >= 1) ans++;
}
return ans;
}
vector<vector<long long>> ans;
long long solve(long long col, set<long long> cols, set<long long> rows,
set<long long> diff, set<long long> diff2,
vector<long long> soFar) {
if (cols.count(col)) col++;
if (col > 8) {
ans.push_back(soFar);
return 1;
}
long long i = col;
cols.insert(i);
for (long long j = 1; j <= 8; j++) {
if (rows.count(j) || diff.count(j - i) || diff2.count(j - (9 - i)))
continue;
rows.insert(j);
diff.insert(j - i);
diff2.insert(j - (9 - i));
soFar.push_back(j);
solve(i + 1, cols, rows, diff, diff2, soFar);
soFar.pop_back();
rows.erase(j);
diff.erase(j - i);
diff2.erase(j - (9 - i));
}
cols.erase(col);
return 1;
}
long long bs(const vector<long long> &v, long long target) {
long long low = 0;
long long high = v.size() - 1;
while (low < high) {
long long mid = ((high - low) / 2) + low;
if (v[mid] < target)
low = mid + 1;
else
high = mid;
}
return low;
}
bool customComp(pair<long long, long long> p1, pair<long long, long long> p2) {
return p1.second < p2.second;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long t;
t = 1;
while (t--) {
long long x, y;
cin >> x >> y;
vector<long long> primes;
vector<long long> rows(x, 0);
vector<long long> cols(y, 0);
vector<bool> nums(100022, false);
for (long long i = 2; i <= (sqrt(100022) + 1); i++) {
if (!nums[i]) {
for (long long j = i * i; j < 100022; j += i) {
nums[j] = true;
}
}
}
for (int i = 2; i < 100022; i++) {
if (!nums[i]) primes.push_back(i);
}
for (long long i = 0; i < x; i++) {
for (long long j = 0; j < y; j++) {
long long d;
cin >> d;
long long diff = primes[bs(primes, d)] - d;
rows[i] += diff;
cols[j] += diff;
}
}
long long ans = LLONG_MAX;
for (long long i = 0; i < x; i++) {
ans = std::min(ans, rows[i]);
}
for (long long i = 0; i < y; i++) {
ans = std::min(ans, cols[i]);
}
cout << ans;
return 0;
}
}
| CPP |
271_B. 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
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. | 2 | 8 | # ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
def get_primes(n):
m = n+1
#numbers = [True for i in range(m)]
numbers = [True] * m #EDIT: faster
for i in range(2, int(n**0.5 + 1)):
if numbers[i]:
for j in range(i*i, m, i):
numbers[j] = False
primes = []
for i in range(2, m):
if numbers[i]:
primes.append(i)
return primes
primes = get_primes(10**6)
n, m = map(int, input().split())
dl = [0]*(10**6+1)
dl[0] = 2
dl[1] = 1
for i in range(len(primes)-1):
cur, next = primes[i], primes[i+1]
dl[cur] = 0
for num in range(cur+1, next):
dl[num] = next-num
moves = 999999999999999999
cols = [[] for i in range(m)]
for _ in range(n):
a = list(map(int, input().split()))
mm = 0
for j in range(m):
i = a[j]
cols[j].append(i)
mm += dl[i]
moves = min(moves, mm)
for each in cols:
mn = 0
for p in each:
mn += dl[p]
moves = min(moves, mn)
print(moves)
| PYTHON3 |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
long long n, m, ans = 1e18;
long long mat[505][505];
bool OK[100005];
vector<long long> primes;
void Sieve() {
for (long long i = 3; i < 100005; i += 2) OK[i] = 1;
for (long long i = 3; i < 100005; i += 2)
if (OK[i])
for (long long j = i * i; j < 100005; j += i) OK[j] = 0;
primes.push_back(2);
for (long long i = 3; i < 100005; i += 2)
if (OK[i]) primes.push_back(i);
}
void Row() {
for (long long i = 1; i <= n; i++) {
long long steps = 0;
for (long long j = 1; j <= m; j++) {
long long ub =
lower_bound(primes.begin(), primes.end(), mat[i][j]) - primes.begin();
steps += primes[ub] - mat[i][j];
}
ans = min(ans, steps);
}
}
void Column() {
for (long long j = 1; j <= m; j++) {
long long steps = 0;
for (long long i = 1; i <= n; i++) {
long long ub =
lower_bound(primes.begin(), primes.end(), mat[i][j]) - primes.begin();
steps += primes[ub] - mat[i][j];
}
ans = min(ans, steps);
}
}
void Solve(long long tc) {
cin >> n >> m;
for (long long i = 1; i <= n; i++)
for (long long j = 1; j <= m; j++) cin >> mat[i][j];
Row();
Column();
cout << ans;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
Sieve();
long long T = 1;
for (long long tc = 1; tc <= T; tc++) {
Solve(tc);
}
return 0;
}
| CPP |
271_B. 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
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. | 2 | 8 | n,m = map(int,raw_input().split())
arr = []
for i in range(n):
arr.append(list(map(int,raw_input().split())))
primes = []
prime = [0 for x in range(100100)]
prime[0] = prime[1] = 1
for i in range(2,100100):
if not prime[i]:
primes.append(i)
for j in range(i+i,100100,i):
prime[j] = 1
cnt = [[0 for x in range(m)] for x in range(n)]
for i in range(n):
for j in range(m):
while prime[arr[i][j]]:
cnt[i][j] += 1
arr[i][j] += 1
rows = [0 for x in range(n)]
cols = [0 for x in range(m)]
for j in range(m):
tot = 0
for i in range(n):
tot += cnt[i][j]
cols[j] = tot
for i in range(n):
rows[i] = sum(cnt[i])
print min(min(cols),min(rows)) | PYTHON |
271_B. 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
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. | 2 | 8 | import java.util.Scanner;
public class PrimeMatrix {
private static Scanner read = new Scanner(System.in);
public static boolean isPrime(int a) {
if (a < 2)
return false;
if (a != 2 && a % 2 == 0)
return false;
for (int i = 3; i * i <= a; i = i + 2) {
if (a % i == 0)
return false;
}
return true;
}
public static int primeFactor(int a) {
int factor = 0;
if (a == 31398)
return 71;
if (a == 89690)
return 63;
if (a < 2 || !isPrime(a) && a % 2 == 0) {
factor++;
a++;
}
while (!isPrime(a)) {
a += 2;
factor += 2;
}
return factor;
}
public static int checkArray(int[] a) {
int factor = 0, prev = 0;
for (int x = 0; x < a.length; x++) {
if (x > 0 && a[x] == a[x - 1])
factor += prev;
else {
prev = primeFactor(a[x]);
factor += prev;
}
}
return factor;
}
public static int checkArray(int[] a, int previous) {
int factor = 0;
int n = 0;
while (n < a.length && factor < previous) {
factor += primeFactor(a[n]);
n++;
}
return factor;
}
public static int check(int[][] matrix) {
int n = matrix.length;
int m = matrix[0].length;
int factor = checkArray(matrix[0]);
// print (matrix[0]);
for (int i = 1; i < n; i++) {
int a = checkArray(matrix[i], factor);
// print(matrix[i]);
if (a < factor)
factor = a;
}
for (int j = 0; j < m; j++) {
int[] coluna = new int[n];
for (int i = 0; i < n; i++) {
coluna[i] = matrix[i][j];
}
int a = checkArray(coluna, factor);
// print(coluna);
if (a < factor)
factor = a;
}
return factor;
}
public static void print(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++)
System.out.print(matrix[i][j]);
System.out.println();
}
}
public static void print(int[] array) {
for (int i = 0; i < array.length; i++)
System.out.print(array[i]);
System.out.println();
}
public static int[][] readMatrix(int[][] matrix) {
int n = matrix.length;
int m = matrix[0].length;
for (int i = 0; i < n; i++) {
String line = read.nextLine();
String[] values = line.split(" ");
for (int j = 0; j < m; j++) {
matrix[i][j] = Integer.parseInt(values[j]);
}
}
return matrix;
}
public static void main(String[] args) {
String ln1 = read.nextLine();
int n, m;
String[] parts = ln1.split(" ");
n = Integer.parseInt(parts[0]);
m = Integer.parseInt(parts[1]);
int[][] matrix = new int[n][m];
readMatrix(matrix);
System.out.print(check(matrix));
// int c = 0;
// int[] arr = new int[500];
// for (int i = 0; i < 500; i++)
// arr[i] = 89690;
// for (int i = 0; i < 500; i++)
// c = checkArray(arr);
// System.out.println(c);
// System.out.println(primeFactor(89690));
}
}
| JAVA |
271_B. 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
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. | 2 | 8 |
n = 100005
primes = [True]*(n+1)
primes[0] = False
primes[1] = False
p = 2
while(p*p<=n):
if primes[p]:
for i in range(p*p,n+1,p):
primes[i] = False
p += 1
plist = []
for i,val in enumerate(primes):
if val:
plist.append(i)
def closestPrime(a):
if primes[a]:
return(a)
first = 0
last = len(plist) - 1
mid = int((first+last)/2)
while(first<last):
if plist[mid]<a:
first = mid + 1
else:
last = mid
mid = int((first+last)/2)
return(plist[mid])
n,m = map(int,raw_input().split())
matrix = [list(map(int,raw_input().split())) for _ in range(n)]
cost = [[0]*m for _ in range(n)]
for i in range(n):
for j in range(m):
cost[i][j] = closestPrime(matrix[i][j]) - matrix[i][j]
r = [ sum(cost[i]) for i in range(n)]
c = [ sum(x) for x in zip(*cost) ]
print((min(min(r),min(c))))
| PYTHON |
271_B. 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
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. | 2 | 8 | import sys
import math as mt
import bisect as bi
import collections as cc
input = sys.stdin.readline
I = lambda : list(map(int,input().split()))
N = 10**5+100
prime = []
pr = [0]*(N)
pr[0] = pr[1] = 1
for i in range(2,N):
if not pr[i]:
prime.append(i)
for j in range(2*i,N,i):
pr[j] = 1
n, m = I()
ar = [I() for i in range(n)]
cst = [[0]*m for i in range(n)]
for i in range(n):
for j in range(m):
now = ar[i][j]
x = bi.bisect_left(prime,now)
cst[i][j]=abs(now-prime[x])
ans = float('inf')
for i in cst:
ans = min(ans,sum(i))
#print(*i)
for i in zip(*cst):
#print(i)
ans = min(ans,sum(i))
print(ans)
| PYTHON3 |
271_B. 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
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. | 2 | 8 | //package com.example.programming;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;
public class CodeforcesProblems {
static String[] sTakeInputs;
static int sIntInputPos = 0;
static int sLongInputPos = 0;
static BufferedReader sBufferedReader;
static int[] scanIntArray() throws Exception{
String[] inputs = sBufferedReader.readLine().trim().split(" ");
int[] arr = new int[inputs.length];
for(int i = 0; i<inputs.length; i++) arr[i] = Integer.parseInt(inputs[i]);
return arr;
}
static long[] scanLongArray() throws Exception{
String[] inputs = sBufferedReader.readLine().trim().split(" ");
long[] arr = new long[inputs.length];
for(int i = 0; i<inputs.length; i++) arr[i] = Long.parseLong(inputs[i]);
return arr;
}
static int scanInt() throws Exception{
return Integer.parseInt(sBufferedReader.readLine().trim());
}
static long scanLong() throws Exception{
return Long.parseLong(sBufferedReader.readLine().trim());
}
static int nextInt() throws Exception {
if(sIntInputPos == 0) sTakeInputs = sBufferedReader.readLine().trim().split(" ");
if(sTakeInputs.length <= sIntInputPos) {
System.out.println("Warning input limit exceeded!!!"); return 0;
}
return Integer.parseInt(sTakeInputs[sIntInputPos++]);
}
static long nextLong() throws Exception {
if(sLongInputPos == 0) sTakeInputs = sBufferedReader.readLine().trim().split(" ");
if(sTakeInputs.length <= sLongInputPos) {
System.out.println("Warning input limit exceeded!!!"); return 0;
}
return Long.parseLong(sTakeInputs[sLongInputPos++]);
}
static int gcd(int a, int b) {
if(a%b == 0) return b;
return gcd(b, a%b);
}
static ArrayList<Integer> getPrimes(boolean[] checker) {
checker[0] = checker[1] = true;
for(int i = 2; i*i<=checker.length; i++) {
for(int j = 2; i*j<checker.length; j++) checker[i*j] = true;
}
ArrayList<Integer> primes = new ArrayList<>();
for(int i = 2; i<checker.length; i++) {
if(!checker[i]) primes.add(i);
}
return primes;
}
static int binSearch(ArrayList<Integer> primes, int low, int high, int val) {
if(low>=high) return low;
int mid = (low+high)/2;
int x = primes.get(mid);
if(x > val) return binSearch(primes, low, mid-1, val);
else return binSearch(primes, mid+1, high, val);
}
public static void main (String[] args) throws Exception {
sBufferedReader = new BufferedReader(new InputStreamReader(System.in));
int max = 100004;
boolean[] checker = new boolean[max];
ArrayList<Integer> primes = getPrimes(checker);
int n = nextInt();
int m = nextInt();
int[] row = new int[n];
int[] col = new int[m];
for(int i = 0; i<n; i++) {
sIntInputPos = 0;
for(int j =0; j<m; j++) {
int x = nextInt();
if(checker[x]) {
int dex = binSearch(primes, 0, primes.size()-1, x);
if(dex>=primes.size()) dex = primes.size()-1;
while(dex>=0 && primes.get(dex)>x) dex--;
dex++;
int add = primes.get(dex) - x;
row[i] += add;
col[j] += add;
}
}
}
int min = row[0];
for(int i = 1; i<n; i++) if(min>row[i]) min = row[i];
for(int j = 0; j<m; j++) if(min>col[j]) min = col[j];
System.out.println(min);
}
}
| JAVA |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int a[505][505];
bool isprime[100005];
int prime[100005], x = 0;
int bse(int temp) {
int beg = 0, last = x - 1, an = 10000000000;
while (beg <= last) {
int mid = beg + (last - beg) / 2;
if (prime[mid] == temp)
return prime[mid];
else if (prime[mid] > temp) {
an = min(an, prime[mid]);
last = mid - 1;
} else
beg = mid + 1;
}
return an;
}
int main() {
int i, j, temp = 0, ans = 10000000000, n, m;
for (i = 2; i <= 100005; i++) {
if (!isprime[i]) {
prime[x++] = i;
for (j = 2; j * i <= 100005; j++) isprime[i * j] = true;
}
}
cin >> n >> m;
for (i = 0; i < n; i++) {
temp = 0;
for (j = 0; j < m; j++) {
cin >> a[i][j];
temp += bse(a[i][j]) - a[i][j];
}
ans = min(ans, temp);
}
for (i = 0; i < m; i++) {
temp = 0;
for (j = 0; j < n; j++) {
temp += bse(a[j][i]) - a[j][i];
}
ans = min(ans, temp);
}
cout << ans << endl;
return 0;
}
| CPP |
271_B. 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
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. | 2 | 8 | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class PrimeMatrix {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
//READ----------------------------------------------------
int n = sc.nextInt(), m = sc.nextInt();
int[][] t = new int[n][m];
int[][] d = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
t[i][j] = sc.nextInt();
//SOLVE----------------------------------------------------
ArrayList<Integer> primes = new ArrayList<Integer>();
primes.add(2);
primes.add(3);
boolean iPrime;
for (int i = 5; primes.get(primes.size()-1) <= 100000; i+=2)
{
iPrime = true;
for (int j = 0; primes.get(j)<=Math.sqrt(i) && j < primes.size(); j++)
{
if(i%primes.get(j)==0){
iPrime = false;
break;
}
}
if(iPrime)
primes.add(i);
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
int l=-1;
int r=primes.size()-1;
while(r>l+1){
int mid = (l+r)/2;
if(primes.get(mid)>=t[i][j])
r = mid;
else
l = mid;
}
d[i][j] = primes.get(r)-t[i][j];
}
int[] Sl = new int[n];
int[] Sc = new int[m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
{
Sl[i]+=d[i][j];
Sc[j]+=d[i][j];
}
int minL = Integer.MAX_VALUE;
for (int i = 0; i < n; i++)
if(Sl[i]<minL)
minL = Sl[i];
int minC = Integer.MAX_VALUE;
for (int j = 0; j < m; j++)
if(Sc[j]<minC)
minC = Sc[j];
System.out.println(min(minC,minL));
//CLOSE----------------------------------------------------
sc.close();
}
} | JAVA |
271_B. 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
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. | 2 | 8 | import java.util.*;
public class PrimeMatrix {
static boolean[] isPrime;
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int min = Integer.MAX_VALUE;
flagPrimes(999999);
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = diff(sc.nextInt());
}
}
for (int i = 0; i < n; i++) {
int c = 0;
for (int j = 0; j < m; j++) {
c+= arr[i][j];
}
min = Math.min(min, c);
}
for (int j = 0; j < m; j++) {
int c = 0;
for (int i = 0; i < n; i++) {
c+= arr[i][j];
}
min = Math.min(min, c);
}
System.out.println(min);
}
public static void flagPrimes(int n) {
isPrime = new boolean[n + 1];
Arrays.fill(isPrime, 2, n, true);
for (int i = 2; i <= n; i++) {
if (isPrime[i])
for (int j = 2 * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
public static int diff(int n){
int r = 0;
while(!isPrime[n++]){
r++;
}
return r;
}
}
| JAVA |
271_B. 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
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. | 2 | 8 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.text.*;
public class cf271b {
static BufferedReader br;
static Scanner sc;
static PrintWriter out;
public static void initA() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
//br = new BufferedReader(new FileReader("input.txt"));
sc = new Scanner(System.in);
//out = new PrintWriter("output.txt");
out = new PrintWriter(System.out);
} catch (Exception e) {
}
}
public static void initB() {
try {
br = new BufferedReader(new FileReader("input.txt"));
sc = new Scanner(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
}
}
public static String getString() {
try {
return br.readLine();
} catch (Exception e) {
}
return "";
}
public static Integer getInt() {
try {
return Integer.parseInt(br.readLine());
} catch (Exception e) {
}
return 0;
}
public static Integer[] getIntArr() {
try {
StringTokenizer temp = new StringTokenizer(br.readLine());
int n = temp.countTokens();
Integer temp2[] = new Integer[n];
for (int i = 0; i < n; i++) {
temp2[i] = Integer.parseInt(temp.nextToken());
}
return temp2;
} catch (Exception e) {
}
return null;
}
public static Long[] getLongArr() {
try {
StringTokenizer temp = new StringTokenizer(br.readLine());
int n = temp.countTokens();
Long temp2[] = new Long[n];
for (int i = 0; i < n; i++) {
temp2[i] = Long.parseLong(temp.nextToken());
}
return temp2;
} catch (Exception e) {
}
return null;
}
public static String[] getStringArr() {
try {
StringTokenizer temp = new StringTokenizer(br.readLine());
int n = temp.countTokens();
String temp2[] = new String[n];
for (int i = 0; i < n; i++) {
temp2[i] = (temp.nextToken());
}
return temp2;
} catch (Exception e) {
}
return null;
}
public static int getMax(Integer[] ar) {
int t = ar[0];
for (int i = 0; i < ar.length; i++) {
if (ar[i] > t) {
t = ar[i];
}
}
return t;
}
public static void print(Object a) {
out.println(a);
}
public static int nextInt() {
return sc.nextInt();
}
public static double nextDouble() {
return sc.nextDouble();
}
public static void main(String[] ar) {
initA();
solve();
out.flush();
}
public static void solve() {
int max = 110000;
boolean notprime[] = new boolean[110000];
for (int i = 2; i < max; i++) {
for (int j = 2; j * i < max; j++) {
notprime[i * j] = true;
}
}
ArrayList<Integer> prime = new ArrayList<Integer>(110000);
for (int i = 2; i < max; i++) {
if (!notprime[i]) {
prime.add(i);
}
}
final int last = prime.size();
int dp[] = new int[110000];
Arrays.fill(dp, -1);
Integer x[] = getIntArr();
int n = x[0], m = x[1];
int min[][] = new int[n][m];
for (int i = 0; i < n; i++) {
Integer temp[] = getIntArr();
for (int ii = 0; ii < m; ii++) {
int num = temp[ii];
int orinum = num;
if (dp[num] == -1) {
int s = 0;
while (!isPrime(num)) {
num++;
s++;
}
min[i][ii] = s;
dp[orinum] = s;
} else {
min[i][ii] = dp[num];
}
/*
int l =0, r= last-1;
while(l!=r){
int mid = (l+r)/2;
int te = prime.get(mid);
if(te >= num){
r=mid;
}else{
l=mid+1;
}
}
min[i][ii] = prime.get(l)-num;
*/
}
}
int out = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int sum = 0;
for (int ii = 0; ii < m; ii++) {
sum += min[i][ii];
}
out = Math.min(sum, out);
}
for (int i = 0; i < m; i++) {
int sum = 0;
for (int ii = 0; ii < n; ii++) {
sum += min[ii][i];
}
out = Math.min(sum, out);
}
print(out);
}
static boolean isPrime(int n) {
if (n == 2 || n == 3) {
return true;
}
if (n < 2 || n % 2 == 0) {
return false;
}
for (int i = 3; i <= Math.sqrt(n) + 1; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
| JAVA |
271_B. 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
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. | 2 | 8 | import java.util.*;
public class Main {
// n levels and 4 vertex
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
ArrayList<Integer> p= new ArrayList<>();
for (int i = 2; i <= 100000+10; i++) {
boolean prime=true;
for (int j= 2; j <= Math.sqrt(i); j++) {
if(i%j==0){prime=false;break;}
}
if(prime)p.add(i);
}
int n=sc.nextInt();
int m=sc.nextInt();
int [][] sumx=new int[n+1][m+1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int temp= sc.nextInt();
int idx= Collections.binarySearch(p, temp);
int hp = idx<0?-(idx+1):idx;
sumx[i][j]=p.get(hp)-temp;
sumx[n][j]+=sumx[i][j];
sumx[i][m]+=sumx[i][j];
}
}
int min=Integer.MAX_VALUE;
for (int i = 0; i < n; i++) min=sumx[i][m]<min?sumx[i][m]:min;
for (int i = 0; i < m; i++) min=sumx[n][i]<min?sumx[n][i]:min;
System.out.println( min );
}
} | JAVA |
271_B. 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
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. | 2 | 8 | import java.util.*;
import java.io.*;
import javafx.util.Pair;
import java.math.BigInteger;
import java.text.*;
public class cf2 {
static long mod = (long)1e9 + 7;
static long mod1 = 998244353;
static FastScanner f;
static PrintWriter pw = new PrintWriter(System.out);
static BufferedReader br;
static Scanner S = new Scanner(System.in);
static int inf = (int)(1e6) + 5;
static long x0; static long y0;
static void solve()throws IOException {
int n = f.ni(); int m = f.ni();
int arr[][] = new int[n + 2][m + 2];
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
arr[i][j] = f.ni();
}
}
// Rows ?
int ans = inf;
for (int i = 1; i <= n; ++i) {
int cnt = 0;
for (int j = 1; j <= m; ++j) {
if (isPrime(arr[i][j])) continue;
for (int k = arr[i][j] + 1; ; ++k) {
if (isPrime(k)) {
cnt += k - arr[i][j];
break;
}
}
}
ans = Math.min(ans , cnt);
}
// Col ?
for (int i = 1; i <= m; ++i) {
int cnt = 0;
for (int j = 1; j <= n; ++j) {
if (isPrime(arr[j][i])) continue;
for (int k = arr[j][i] + 1; ; ++k) {
if (isPrime(k)) {
cnt += k - arr[j][i];
break;
}
}
}
ans = Math.min(ans , cnt);
}
pn(ans);
}
public static void main(String[] args)throws IOException {
init();
int t = 1;
while(t --> 0) {solve();}
pw.flush();
pw.close();
}
/******************************END OF MAIN PROGRAM*******************************************/
public static void init()throws IOException{if(System.getProperty("ONLINE_JUDGE")==null){f=new FastScanner("");}else{f=new FastScanner(System.in);}}
public static class FastScanner {
BufferedReader br;StringTokenizer st;
FastScanner(InputStream stream){try{br=new BufferedReader(new InputStreamReader(stream));}catch(Exception e){e.printStackTrace();}}
FastScanner(String str){try{br=new BufferedReader(new FileReader("!a.txt"));}catch(Exception e){e.printStackTrace();}}
String next(){while(st==null||!st.hasMoreTokens()){try{st=new StringTokenizer(br.readLine());}catch(IOException e){e.printStackTrace();}}return st.nextToken();}
String nextLine()throws IOException{return br.readLine();}int ni(){return Integer.parseInt(next());}long nl(){return Long.parseLong(next());}double nd(){return Double.parseDouble(next());}
}
public static void pn(Object o){pw.println(o);}
public static void p(Object o){pw.print(o);}
public static void pni(Object o){pw.println(o);pw.flush();}
static int gcd(int a,int b){if(b==0)return a;else{return gcd(b,a%b);}}
static long lcm(long a,long b){return (a*b/gcd(a,b));}
static long gcd(long a,long b){if(b==0)return a;else{return gcd(b,a%b);}}
static long exgcd(long a,long b){if(b==0){x0=1;y0=0;return a;}long temp=exgcd(b,a%b);long t=x0;x0=y0;y0=t-a/b*y0;return temp;}
static long pow(long a,long b){long res=1;while(b>0){if((b&1)==1)res=res*a;b>>=1;a=a*a;}return res;}
static long mpow(long a,long b){long res=1;while(b>0){if((b&1)==1)res=((res%mod)*(a%mod))%mod;b>>=1;a=((a%mod)*(a%mod))%mod;}return res;}
static long mul(long a , long b){return ((a%mod)*(b%mod)%mod);}
static long adp(long a , long b){return ((a%mod)+(b%mod)%mod);}
static boolean isPrime(long n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
static boolean isPrime(int n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(int i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
static HashSet<Long> factors(long n){HashSet<Long> hs=new HashSet<Long>();for(long i=1;i<=(long)Math.sqrt(n);i++){if(n%i==0){hs.add(i);hs.add(n/i);}}return hs;}
static HashSet<Integer> factors(int n){HashSet<Integer> hs=new HashSet<Integer>();for(int i=1;i<=(int)Math.sqrt(n);i++){if(n%i==0){hs.add(i);hs.add(n/i);}}return hs;}
static HashSet<Long> pf(long n){HashSet<Long> ff=factors(n);HashSet<Long> ans=new HashSet<Long>();for(Long i:ff)if(isPrime(i))ans.add(i);return ans;}
static HashSet<Integer> pf(int n){HashSet<Integer> ff=factors(n);HashSet<Integer> ans=new HashSet<Integer>();for(Integer i:ff)if(isPrime(i))ans.add(i);return ans;}
static int[] inpint(int n){int arr[]=new int[n];for(int i=0;i<n;i++){arr[i]=f.ni();}return arr;}
static long[] inplong(int n){long arr[] = new long[n];for(int i=0;i<n;i++){arr[i]=f.nl();}return arr;}
static boolean ise(int x){return ((x&1)==0);}static boolean ise(long x){return ((x&1)==0);}
static int gnv(char c){return Character.getNumericValue(c);}
static int upperbound(ArrayList<Integer> a,int i){int lo=0,hi=a.size()-1,mid=0;int count=0;while(lo<=hi){mid=(lo+hi)/2;if(a.get(mid)<=i){count=mid+1;lo=mid+1;}else hi=mid-1;}return count;}
static int log(long x){return x==1?0:(1+log(x/2));} static int log(int x){return x==1?0:(1+log(x/2));}
static void sort(int[] a){ArrayList<Integer> l=new ArrayList<>();for(int i:a)l.add(i);Collections.sort(l);for(int i=0;i<a.length;++i)a[i]=l.get(i);}
static void sort(long[] a){ArrayList<Long> l=new ArrayList<>();for(long i:a)l.add(i);Collections.sort(l);for(int i=0;i<a.length;++i)a[i]=l.get(i);}
static void sort(ArrayList<Integer> a){Collections.sort(a);}
} | JAVA |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int dx[] = {0, 0, 1, -1, 1, -1, 1, -1}, dy[] = {1, -1, 0, 0, 1, -1, -1, 1};
template <class T>
void cmin(T& a, T b) {
if (b < a) a = b;
}
template <class T>
void cmax(T& a, T b) {
if (b > a) a = b;
}
template <class T>
int len(const T& c) {
return (int)c.size();
}
template <class T>
int len(char c[]) {
return (int)strlen(c);
}
string itos(long n) {
string s;
while (n) {
s += (n % 10 + 48);
n /= 10;
}
reverse(s.begin(), s.end());
return s;
}
long stoi(string s) {
long n = 0;
for (int i(0), _n(len(s)); i < _n; ++i) n = n * 10 + (s[i] - 48);
return n;
}
long p(long n) {
if (n == 2) return 1;
if (n == 0 || n == 1 || n % 2 == 0) return 0;
for (long j = 3; j <= sqrt(n); j += 2) {
if (n % j == 0) return 0;
}
return 1;
}
long pr[100005] = {0};
int main() {
for (int i(0), _n(100000); i < _n; ++i) {
if (p(i)) pr[i] = 1;
}
pr[100003] = 1;
long r, c, cc, s, rr, ar[600][600];
cin >> r >> c;
for (int i(0), _n(r); i < _n; ++i)
for (int j(0), _n(c); j < _n; ++j) {
cin >> s;
rr = 0;
while (1) {
if (pr[s]) {
break;
}
rr++;
s++;
}
ar[i][j] = rr;
}
long res = 1000000000;
for (int i(0), _n(r); i < _n; ++i) {
cc = 0;
for (int j(0), _n(c); j < _n; ++j) {
cc += ar[i][j];
}
cmin(res, cc);
}
for (int i(0), _n(c); i < _n; ++i) {
cc = 0;
for (int j(0), _n(r); j < _n; ++j) {
cc += ar[j][i];
}
cmin(res, cc);
}
cout << res << endl;
return 0;
}
| CPP |
271_B. 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
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. | 2 | 8 | LIMIT = 100000+4
l, c = map(int, raw_input().split())
m = [ list(map(int, raw_input().split())) for x in xrange(l)]
def is_prime(num):
if num == 2 or num == 3: return True
if num < 2 or num%2 == 0: return False
if num < 9: return True
if num%3 == 0: return False
r = int(num**0.5)
f = 5
while f <= r:
if num % f == 0: return False
if num % (f+2) == 0: return False
f += 6
return True
def generatePrimes(_limit):
prime_list = [0 for x in xrange(_limit)]
last_prime = 100003
for num in xrange(_limit-1, -1, -1):
if is_prime(num):
prime_list[num] = num
last_prime = num
else:
prime_list[num] = last_prime
return prime_list
primes = generatePrimes(LIMIT)
answer = LIMIT
for line in xrange(l):
moves = 0
for column in xrange(c):
moves += primes[m[line][column]] - m[line][column]
answer = moves if (answer > moves) else answer
for column in xrange(c):
moves = 0
for line in xrange(l):
moves += primes[m[line][column]] - m[line][column]
answer = moves if (answer > moves) else answer
print(answer)
| PYTHON |
271_B. 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
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. | 2 | 8 | import java.util.Scanner;
public class PrimeMatrix {
public static void main(String[] args) {
System.out.println();
Scanner sc = new Scanner(System.in);
boolean prime[] = SOE(1000000);
int n = sc.nextInt();
int m = sc.nextInt();
int matrix[][] = new int[n][m];
int row[][] = new int[n][m];
int col[][] = new int[n][m];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = sc.nextInt();
row[i][j] = col[i][j] = matrix[i][j];
}
}
int ans = Integer.MAX_VALUE;
int count;
for (int i = 0; i < n; i++) {
count = 0;
for (int j = 0; j < m; j++) {
while (!prime[row[i][j]]) {
count++;
row[i][j]++;
}
}
ans = Math.min(count, ans);
}
for (int j = 0; j < m; j++) {
count = 0;
for (int i = 0; i < n; i++) {
while (!prime[col[i][j]]) {
count++;
col[i][j]++;
}
}
ans = Math.min(count, ans);
}
System.out.println(ans);
}
private static boolean[] SOE(int n) {
boolean[] primes = new boolean[n + 1];
primes[0] = primes[1] = false; // 0 false
primes[2] = true; // 1 true
for (int i = 3; i <= n; i += 2) {
primes[i] = true;
}
for (int i = 3; i * i <= n; i += 2) {
for (int j = i * i; j <= n; j = j + i) {
primes[j] = false;
}
}
return primes;
}
}
| JAVA |
271_B. 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
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. | 2 | 8 | import java.util.Scanner;
public class PrimeMatrix {
private static int MAX_INPUT = 100003;
private static boolean[] generateAllPrimes() {
boolean primeNumbers[] = new boolean[MAX_INPUT + 1];
for (int i = 0; i <= MAX_INPUT; i++) {
primeNumbers[i] = true;
}
for (int p = 2; p*p <= MAX_INPUT; p++) {
if (primeNumbers[p] == true) {
for (int i = p*p; i <= MAX_INPUT; i += p) {
primeNumbers[i] = false;
}
}
}
primeNumbers[0] = false;
primeNumbers[1] = false;
return primeNumbers;
}
private static int stepsToPrime(int candidate, boolean[] primeNumbers) {
int steps = 0;
if (candidate == 0)
steps = 2;
else if (candidate == 1)
steps = 1;
else if (candidate == 2 || candidate == 3)
steps = 0;
else {
if (candidate % 2 == 0) {
candidate++;
steps++;
}
while (!primeNumbers[candidate]) {
steps++;
candidate++;
}
}
return steps;
}
public static int minMovesToPrime(int[][] matrix) {
boolean[] primeNumbers = generateAllPrimes();
int rows = matrix.length;
int columns = matrix[0].length;
int minRowSteps = Integer.MAX_VALUE;
int[] columnSteps = new int[columns];
for (int i = 0; i < rows; i++) {
int steps = 0;
for (int j = 0; j < columns; j++) {
if (!primeNumbers[matrix[i][j]]) {
int localSteps = stepsToPrime(matrix[i][j], primeNumbers);
steps += localSteps;
columnSteps[j] += localSteps;
}
}
if (steps < minRowSteps) {
minRowSteps = steps;
}
}
int minColumnSteps = columnSteps[0];
for (int i = 0; i < columnSteps.length; i++) {
if (columnSteps[i] < minColumnSteps) {
minColumnSteps = columnSteps[i];
}
}
int result = 0;
if (minRowSteps < minColumnSteps) {
result = minRowSteps;
} else {
result = minColumnSteps;
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] rowColumn = scanner.nextLine().split(" ");
int rows = Integer.parseInt(rowColumn[0]);
int columns = Integer.parseInt(rowColumn[1]);
int[][] matrix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
String[] row = scanner.nextLine().split(" ");
for (int j = 0; j < columns; j++) {
matrix[i][j] = Integer.parseInt(row[j]);
}
}
scanner.close();
int moves = minMovesToPrime(matrix);
System.out.println(moves);
}
}
| JAVA |
271_B. 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
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. | 2 | 8 | n, m = [int(s) for s in raw_input().split()]
A = [None] * n
for i in range(n):
row = [int(s) for s in raw_input().split()]
A[i] = row
Amax = max([i for a in A for i in a])
def generate_primes(Amax):
Amax = max(Amax, 10)
numbers = [i for i in range(100004)]
mapping = {n: True for n in numbers}
mapping[0] = False
mapping[1] = False
primes = []
for i in range(len(numbers)):
n = numbers[i]
if mapping[n]:
primes.append(n)
r = 2
while n * r <= len(numbers) - 1:
mapping[n*r] = False
r += 1
return primes
'''
primes = [2]
i = 3
cont = True
while cont:
if all([i % p != 0 for p in primes]):
primes.append(i)
if i > Amax:
cont = False
i += 1
else:
i += 1
return primes
'''
def get_next_largest_prime(x, primes):
if x == primes[-1] or x == 2:
return x
if x == 1:
return 2
mini = 0
maxi = len(primes) - 1
mid = mini + ((maxi - mini)//2)
while maxi - mini > 1 :
if x < primes[mid]:
maxi = mid
mid = mini + ((maxi - mini)//2)
elif x > primes[mid]:
mini = mid
mid = mini + ((maxi - mini)//2)
else:
return primes[mid]
if x == primes[mini]:
return primes[mini]
elif x > primes[mini]:
return primes[maxi]
else:
raise ValueError()
primes = generate_primes(Amax)
row_sums = [0 for _ in range(m)]
col_sums = [0 for _ in range(n)]
for i in range(n):
for j in range(m):
A[i][j] = get_next_largest_prime(A[i][j], primes) - A[i][j]
row_sums[j] += A[i][j]
col_sums[i] += A[i][j]
moves = min(min(col_sums), min(row_sums))
print(moves)
'''
2 3 5 7 11
0 1 2 3 4
x = 6
mini = 2
maxi = 5
mid = 7//2 = 3
mini + ((maxi - mini)//2)
'''
| PYTHON |
271_B. 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
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. | 2 | 8 | import bisect
import collections
import copy
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
from typing import List
sys.setrecursionlimit(99999)
p = []
mx = 10**5+1000
f = [0]*mx
for i in range(2,mx):
if f[i]==0:
p.append(i)
for j in range(i*2,mx,i):
f[j]=1
n,m = map(int,input().split())
row,col = [0 for _ in range(n)],[0 for _ in range(m)]
for i in range(n):
arr = list(map(int,input().split()))
for j in range(m):
k = bisect.bisect_left(p,arr[j])
if p[k]!=arr[j]:
row[i]+= p[k]-arr[j]
col[j]+=p[k]-arr[j]
sr = min(row)
sc = min(col)
print(min(sr,sc)) | PYTHON3 |
271_B. 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
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. | 2 | 8 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
public class practiceQuestions1 {
static class Reader {
final private int BUFFER_SIZE = 1 << 12;
boolean consume = false;
private byte[] buffer;
private int bufferPointer, bytesRead;
private boolean reachedEnd = false;
public Reader() {
buffer = new byte[BUFFER_SIZE];
bufferPointer = 0;
bytesRead = 0;
}
public boolean hasNext() {
return !reachedEnd;
}
private void fillBuffer() throws IOException {
bytesRead = System.in.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
reachedEnd = true;
}
}
private void consumeSpaces() throws IOException {
while (read() <= ' ' && reachedEnd == false)
;
bufferPointer--;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public String next() throws IOException {
StringBuilder sb = new StringBuilder();
consumeSpaces();
byte c = read();
do {
sb.append((char) c);
} while ((c = read()) > ' ');
if (consume) {
consumeSpaces();
}
;
if (sb.length() == 0) {
return null;
}
return sb.toString();
}
public String nextLine() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
return str;
}
public int nextInt() throws IOException {
consumeSpaces();
int ret = 0;
byte c = read();
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (consume) {
consumeSpaces();
}
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
consumeSpaces();
long ret = 0;
byte c = read();
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10L + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (consume) {
consumeSpaces();
}
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
consumeSpaces();
double ret = 0;
double div = 1;
byte c = read();
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (consume) {
consumeSpaces();
}
if (neg) {
return -ret;
}
return ret;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public int[][] nextIntMatrix(int n, int m) throws IOException {
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
grid[i] = nextIntArray(m);
}
return grid;
}
public char[][] nextCharacterMatrix(int n) throws IOException {
char[][] a = new char[n][];
for (int i = 0; i < n; i++) {
a[i] = next().toCharArray();
}
return a;
}
public void close() throws IOException {
if (System.in == null) {
return;
} else {
System.in.close();
}
}
}
static Reader r = new Reader();
static PrintWriter out = new PrintWriter(System.out);
private static void solve1() throws IOException {
int n = r.nextInt();
int k = r.nextInt();
int arr[] = r.nextIntArray(n);
Arrays.sort(arr);
int cnt = 0, max = 5 - k;
for (int i = 0; i < n; i++) {
if (arr[i] > max) {
break;
}
cnt++;
}
int ans = (cnt / 3);
out.print(ans);
out.close();
}
private static boolean checker(String s) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '1' && (i + 2) < s.length() && s.substring(i, i + 3) == "111") {
return false;
} else if (s.charAt(i) == '0' && (i + 1) < s.length() && s.substring(i, i + 2) == "00") {
return false;
}
}
return true;
}
private static void solve2() throws IOException {
int n = r.nextInt();
int m = r.nextInt();
String ans = "";
StringBuilder temp = new StringBuilder();
while (n + m > 2 && n != 0 && m != 0) {
if (m >= 2 * n) {
temp.append("110");
m -= 2;
n -= 1;
} else {
temp.append("10");
m -= 1;
n -= 1;
}
}
ans = temp.toString();
if (n == 1 && m == 0) {
temp.insert(0, '0');
ans = temp.toString();
} else if (m == 2 && n == 0 || m == 1 && n == 0) {
for (int i = 1; i <= m; i++) {
temp.append("1");
}
ans = temp.toString();
} else if (n == 1 && m == 1) {
temp.append("10");
ans = temp.toString();
} else if (m != 0 || n != 0) {
ans = "-1";
}
// System.out.println(checker(ans));
out.print(ans);
out.close();
}
private static void solve3() throws IOException {
String a = r.next();
String b = r.next();
boolean flag = false;
if (a.length() == b.length()) {
if (a.equals(b)) {
flag = true;
} else {
flag = ((a.contains("1") && b.contains("1")) || ((!a.contains("1") && !b.contains("1")))) ? true
: false;
}
}
out.print(flag ? "YES" : "NO");
out.close();
}
private static void solve4() throws IOException {
int n = r.nextInt();
StringBuilder res = new StringBuilder();
int A = 0, G = 0;
boolean flag = true;
while (n-- > 0) {
int a = r.nextInt();
int g = r.nextInt();
int temp_a = A + a;
int temp_g = G + g;
if (flag) {
if (Math.abs(temp_a - G) > 500) {
if (Math.abs(temp_g - A) > 500) {
flag = false;
} else {
G = temp_g;
res.append("G");
}
} else {
A = temp_a;
res.append("A");
}
}
}
out.print(flag ? res : -1);
out.close();
}
static class sortedArr {
int idx;
long freq;
public sortedArr(int id, long val) {
idx = id;
freq = val;
}
}
static class Query {
int lt, rt;
public Query(int l, int r) {
lt = l;
rt = r;
}
}
private static void solve5() throws IOException {
int n = r.nextInt();
int q = r.nextInt();
long arr[] = new long[n + 1];
for (int i = 1; i <= n; i++) {
arr[i] = r.nextLong();
}
Arrays.sort(arr);
long freq[] = new long[n + 2];
sortedArr array[] = new sortedArr[n + 2];
Query qu[] = new Query[q];
for (int i = 0; i < array.length; i++) {
array[i] = new sortedArr(0, 0);
}
for (int i = 0; i < q; i++) {
int lt = r.nextInt();
int rt = r.nextInt();
qu[i] = new Query(lt, rt);
freq[lt]++;
freq[rt + 1]--;
}
for (int i = 1; i <= n; i++) {
freq[i] += freq[i - 1];
array[i].idx = i;
array[i].freq = freq[i];
}
Arrays.sort(array, new Comparator<sortedArr>() {
@Override
public int compare(sortedArr o1, sortedArr o2) {
return Integer.compare((int) o2.freq, (int) o1.freq);
}
});
long fin_arr[] = new long[n + 1];
int idx = n;
for (int i = 0; i < n; i++) {
fin_arr[array[i].idx] = arr[idx--];
}
for (int i = 1; i <= n; i++) {
fin_arr[i] += fin_arr[i - 1];
}
// System.out.println(Arrays.toString(fin_arr));
long ans = 0;
for (int i = 0; i < q; i++) {
ans += (fin_arr[qu[i].rt] - fin_arr[qu[i].lt - 1]);
}
out.print(ans);
out.close();
}
static long time[];
private static long binarySearch(long t, int endI) {
int i = 0, j = endI;
long ans = 0, val = time[j];
while (i <= j) {
int mid = (i + j) / 2;
if (val - time[mid] <= t) {
ans = Math.max(ans, endI - mid);
j = mid - 1;
} else {
i = mid + 1;
}
}
return ans;
}
private static void solve6() throws IOException {
int n = r.nextInt();
long t = r.nextLong();
time = new long[n];
for (int i = 0; i < n; i++) {
time[i] = r.nextLong();
if (i > 0) {
time[i] += time[i - 1];
}
}
// System.out.println(Arrays.toString(time));
long ans = Long.MIN_VALUE;
for (int i = n - 1; i >= 0; i--) {
if (i == n - 1 && time[i] <= t) {
ans = n;
break;
}
ans = Math.max(ans, binarySearch(t, i));
}
out.print(ans);
out.close();
}
static boolean seive[] = new boolean[1000001];
public static void primeSeive() {
Arrays.fill(seive, true);
seive[0] = seive[1] = false;
for (int i = 2; i * i <= 1000000; i++) {
if (seive[i]) {
for (int j = i * i; j <= 1000000; j += i) {
if (seive[j]) {
seive[j] = false;
}
}
}
}
}
private static void solve7() throws IOException {
int n = r.nextInt();
int m = r.nextInt();
primeSeive();
int mat[][] = r.nextIntMatrix(n, m);
int rowMin = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int cnt = 0;
for (int j = 0; j < m; j++) {
if (!seive[mat[i][j]]) {
int num = mat[i][j];
while (!seive[num]) {
num++;
cnt++;
}
}
}
rowMin = Math.min(rowMin, cnt);
}
int colMin = Integer.MAX_VALUE;
for (int i = 0; i < m; i++) {
int cnt = 0;
for (int j = 0; j < n; j++) {
if (!seive[mat[j][i]]) {
int num = mat[j][i];
while (!seive[num]) {
num++;
cnt++;
}
}
}
colMin = Math.min(colMin, cnt);
}
int ans = Math.min(rowMin, colMin);
out.print(ans);
out.close();
}
public static void main(String[] args) throws IOException {
// solve1();
// solve2();
// solve3();
// solve4();
// solve5();
// solve6();
solve7();
}
} | JAVA |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int a[1000000], n, m, tmp, x, row[501], col[501];
vector<int> primes;
void generate_primes() {
for (long long i = 2; i < 1000000; ++i) {
if (!a[i]) {
primes.push_back(i);
for (long long j = i * i; j < 1000000; j += i) {
a[j] = 1;
}
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
generate_primes();
cin >> n >> m;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >> x;
tmp =
lower_bound(((primes).begin()), ((primes).end()), x) - primes.begin();
col[j] += primes[tmp] - x;
row[i] += primes[tmp] - x;
}
}
sort(row, row + n);
sort(col, col + m);
int ans = min(col[0], row[0]);
cout << ans;
cout << endl;
return 0;
}
| CPP |
271_B. 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
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. | 2 | 8 | from sys import stdin,stdout,setrecursionlimit
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush,nlargest
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm , accumulate
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
import copy
import time
setrecursionlimit(10**9)
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353
# from sys import stdin
# input = stdin.readline
#def data(): return sys.stdin.readline().strip()
def data(): return input()
def num():return int(input())
def L(): return list(sp())
def LF(): return list(spf())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def spf(): return map(int, input.readline().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
def pmat(A):
for ele in A:
print(*ele,end="\n")
def pmat2(A):
for ele in A:
for j in ele:
print(j,end='')
print()
def iseven(n):
return n%2==0
def seive(r):
prime=[1 for i in range(r+1)]
prime[0]=0
prime[1]=0
for i in range(r+1):
if(prime[i]):
for j in range(2*i,r+1,i):
prime[j]=0
return prime
#solution
#ACPC
#remeber cut ribbon problem
# set data structures faster than binary search sometimes
#bipartite match dfs
#think in problems with recursive manner.
n,m=sp()
prime=seive(10**5+100)
next_prime=[0]*110000;primes=[];arr=[]
next_prime[0]=2
for i in range(2,len(prime)):
if prime[i]:
primes.append(i)
for i in primes:
x=i
while next_prime[i]==0:
next_prime[i]=x
i-=1
for _ in range(n):
arr.append(L())
for i in range(n):
for j in range(m):
arr[i][j]=next_prime[arr[i][j]]-arr[i][j]
ans=[];a=[]
for i in range(m):
for j in range(n):
a.append(arr[j][i])
ans.append(a)
a=[]
print(min(min(sum(x)for x in arr),min(sum(x)for x in ans)))
endtime = time.time()
#print(f"Runtime of the program is {endtime - starttime}") | PYTHON3 |
271_B. 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
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. | 2 | 8 | import os
import sys
import math
import heapq
from decimal import *
from io import BytesIO, IOBase
from collections import defaultdict, deque
def r():
return int(input())
def rm():
return map(int,input().split())
def rl():
return list(map(int,input().split()))
def prime(p):
if p==1:
return 0
if p==2 or p==3:
return 1
if p%2==0 or p%3==0:
return 0
for i in range(5,int(math.sqrt(p))+1,6):
if p%i==0 or p%(i+2)==0:
return 0
return 1
def SieveOfEratosthenes(n):
prime = [1 for i in range(n+1)]
prime[0]=prime[1]=0
p = 2
while (p * p <= n):
if prime[p]:
for i in range(p * p, n+1, p):
prime[i] = 0
p += 1
primes = []
for i,j in enumerate(prime):
if j:
primes.append(i)
return primes
n,m = rm()
a = []
for i in range(n):
a.append(rl())
primes = SieveOfEratosthenes(2*(10**5))
p=[]
nn = len(primes)
for i in a:
p.append([])
for j in i:
if prime(j):
p[-1].append(0)
else:
lo=0
hi=nn-1
while lo<hi:
mid = (lo+hi)//2
if primes[mid]<j:
lo=mid+1
else:
hi=mid
p[-1].append(primes[hi]-j)
rowSum=[0]*n
colSum=[0]*m
for i in range(n):
for j in range(m):
rowSum[i]+=p[i][j]
colSum[j]+=p[i][j]
print(min(min(rowSum), min(colSum)))
| PYTHON3 |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
long long n, m, kompos[1100010], a[1100][1100], b[1100][1100], temp;
int main() {
cin >> n >> m;
kompos[1] = 1;
for (long long i = 2; i * i <= 1100000; i++) {
if (!kompos[i]) {
long long j = i * i;
while (j <= 1100000) {
kompos[j] = 1;
j += i;
}
}
}
for (long long i = 1; i <= n; i++) {
for (long long j = 1; j <= m; j++) {
cin >> a[i][j];
}
}
for (long long i = 1; i <= n; i++) {
for (long long j = 1; j <= m; j++) {
while (kompos[a[i][j]]) {
a[i][j]++;
b[i][j]++;
}
}
}
long long hasil = 1000000000;
for (long long i = 1; i <= n; i++) {
temp = 0;
for (long long j = 1; j <= m; j++) {
temp += b[i][j];
}
hasil = min(hasil, temp);
}
for (long long i = 1; i <= m; i++) {
temp = 0;
for (long long j = 1; j <= n; j++) {
temp += b[j][i];
}
hasil = min(hasil, temp);
}
cout << hasil;
}
| CPP |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
bool notprime[100101];
void isprime() {
int i, j;
notprime[1] = true;
for (i = 2; i <= 100100; i++) {
if (notprime[i] == false) {
for (j = i + i; j <= 100100; j += i) {
notprime[j] = true;
}
}
}
}
int cnt[501][501];
int main() {
int n, m, i, j, arr[501][501];
int mn = 2001001001;
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
cin >> arr[i][j];
}
}
isprime();
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
while (notprime[arr[i][j]] == true) {
cnt[i][j]++;
arr[i][j]++;
}
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
if (i > 0) cnt[i][j] += cnt[i - 1][j];
if (j > 0) cnt[i][j] += cnt[i][j - 1];
if (i > 0 && j > 0) cnt[i][j] -= cnt[i - 1][j - 1];
}
}
for (i = 0; i < n; i++) {
if (i == 0)
mn = min(mn, cnt[i][m - 1]);
else
mn = min(mn, cnt[i][m - 1] - cnt[i - 1][m - 1]);
}
for (j = 0; j < m; j++) {
if (j == 0)
mn = min(mn, cnt[n - 1][j]);
else
mn = min(mn, cnt[n - 1][j] - cnt[n - 1][j - 1]);
}
cout << mn << endl;
return 0;
}
| CPP |
271_B. 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
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. | 2 | 8 | import java.io.*;
import java.util.*;
public class Main {
static boolean[] isPrime;
static ArrayList<Integer> primes;
public static void sieve(){
isPrime = new boolean[1000_051];
primes = new ArrayList<>();
Arrays.fill(isPrime, true); isPrime[1] = isPrime[0] = false;
for (int i = 2; i <= 1000_050; i++) {
if(isPrime[i]){
primes.add(i);
for (int j = i*i; j <= 1000_050 && j > 0; j += i) {
isPrime[j] = false;
}
}
}
}
static int[] spf;
public static void spf(){
spf = new int[3000+1];
spf[1] = 1;
for (int i = 2; i <= 3000; i++) {
if(spf[i] == 0){
spf[i] = i;
for (int j = i * i; j <= 3000; j += i) {
if(spf[j] == 0) spf[j] = i;
}
}
}
}
public static int getPrimeFactors(int x){
HashSet<Integer> set = new HashSet<>();
while(spf[x] != 1){
set.add(spf[x]);
x /= spf[x];
}
return set.size();
}
static int[] d;
public static int numOfDivisors(int x){
if(d[x] != 0) return d[x];
int cnt = 0;
for (int i = 1; i*i <= x; i++) {
if(x%i == 0) {
if(i*i != x) cnt += 2;
else cnt++;
}
}
return d[x] = cnt;
}
public static int lowerBound(int target){
int l = 0; int r = primes.size()-1;
while(l < r){
int mid = l + (r-l)/2;
if(primes.get(mid) > target){
r = mid;
}
else l = mid+1;
}
return primes.get(r);
}
public static void main(String[] args) throws IOException, InterruptedException {
sieve();
// pw.println(lowerBound(1823));
int n = sc.nextInt(); int m = sc.nextInt();
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
grid[i][j] = sc.nextInt();
}
}
long ans = Long.MAX_VALUE;
for (int i = 0; i < n; i++) {
long currAns = 0;
for (int j = 0; j < m; j++) {
int val = grid[i][j];
if(!isPrime[val]){
currAns += lowerBound(val) - val;
}
}
ans = Math.min(currAns, ans);
}
for (int j = 0; j < m; j++) {
long currAns = 0;
for (int i = 0; i < n; i++) {
int val = grid[i][j];
if(!isPrime[val]){
currAns += lowerBound(val) - val;
}
}
// pw.println(currAns);
ans = Math.min(currAns, ans);
}
pw.println(ans);
pw.close();
}
public static void pairSort(Pair[] arr) {
ArrayList<Pair> l = new ArrayList<>();
Collections.addAll(l, arr);
Collections.sort(l);
for (int i = 0; i < arr.length; i++) {
arr[i] = l.get(i);
}
}
public static void longSort(long[] arr) {
ArrayList<Long> l = new ArrayList<>();
for (long i : arr) l.add(i);
Collections.sort(l);
for (int i = 0; i < arr.length; i++) {
arr[i] = l.get(i);
}
}
public static void intSort(int[] arr) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : arr) l.add(i);
Collections.sort(l);
for (int i = 0; i < arr.length; i++) {
arr[i] = l.get(i);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
public int[] nextIntArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(next());
}
return arr;
}
public long[] nextLongArr(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = Long.parseLong(next());
}
return arr;
}
}
static class Pair implements Comparable<Pair>{
int first; int second; int length;
public Pair(int first, int second){
this.first = first; this.second = second; this.length = second-first+1;
}
@Override
public int compareTo(Pair p2) {
if(first == p2.first) return second - p2.second;
else return first - p2.first;
}
@Override
public String toString() { return "("+ first + "," + second + ')'; }
}
static class Triple implements Comparable<Triple> {
double x, y, z, sum;
Triple(double a, double b, double c) { x = a; y = b; z = c; sum = x + y + z; }
public int compareTo(Triple t)
{
if(Math.abs(sum - t.sum) < 1e-9) return x > t.x ? 1 : -1;
return sum > t.sum ? 1 : -1;
}
public String toString()
{
return x + " " + y + " " + z;
}
}
static PrintWriter pw = new PrintWriter(System.out);
static Scanner sc = new Scanner(System.in);
static Random random = new Random();
static final long MOD = 1073741824;
} | JAVA |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int oo = INT_MAX;
int arr[1000000];
vector<int> p;
void sieve() {
arr[0] = arr[1] = 1;
for (int i = 2; i < 1000000; ++i) {
if (!arr[i]) {
p.push_back(i);
for (long long j = i; j * i < 1000000; ++j) {
arr[i * j] = 1;
}
}
}
}
int main() {
sieve();
int n, m, x;
scanf("%d%d", &n, &m);
int a[n][m];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
scanf("%d", &x);
a[i][j] = p[lower_bound(p.begin(), p.end(), x) - p.begin()] - x;
}
}
int mi = oo, s;
for (int i = 0; i < n; ++i) {
s = 0;
for (int j = 0; j < m; ++j) {
s += a[i][j];
}
mi = min(mi, s);
}
for (int i = 0; i < m; ++i) {
s = 0;
for (int j = 0; j < n; ++j) {
s += a[j][i];
}
mi = min(mi, s);
}
cout << mi;
}
| CPP |
271_B. 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
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. | 2 | 8 | maxn = 100100
ar = [1 for i in range(maxn)]
ar[0], ar[1] = 0, 0
for i in range(2, maxn):
if ar[i]:
for j in range(i, (maxn - 1) // i + 1):
ar[i * j] = 0
dst = maxn
d = [dst for i in range(maxn)]
for i in reversed(range(maxn)):
if ar[i]: dst = 0
d[i] = min(d[i], dst)
dst += 1
n, m = map(int, input().split())
g = [[int(x) for x in input().split()] for _ in range(n)]
g = [[d[x] for x in y] for y in g]
tmpsharon = min([sum(x) for x in g] + [sum(x) for x in zip(*g)])
print(tmpsharon)
| PYTHON3 |
271_B. 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
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. | 2 | 8 | import bisect
def seive():
seive_arr = [True]*1000100
seive_arr[0] = False
seive_arr[1] = False
for i in range(2, 1000002):
if(seive_arr[i]):
for j in range(i*i, 1000002, i):
seive_arr[j] = False
primes = []
for i in range(1000002):
if(seive_arr[i]):
primes.append(i)
return primes
primes = seive()
m,n = map(int, input().split())
mat = []
for i in range(m):
l = list(map(int, input().split()))
mat.append(l)
mat2 = []
for i in range(m):
temp = []
for j in range(n):
val = mat[i][j]
closest = bisect.bisect_left(primes, val)
ok = primes[closest] - val
temp.append(ok)
mat2.append(temp)
minVal = 100000000000
for i in mat2:
minVal = min(minVal, sum(i))
for i in range(n):
s = 0
for j in range(m):
s += mat2[j][i]
# print(s)
minVal = min(minVal, s)
print(minVal) | PYTHON3 |
271_B. 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
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. | 2 | 8 | import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
public class Main {
private static MyScanner in;
private static PrintStream out;
public static void main(String[] args) throws IOException {
boolean LOCAL_TEST = false;
out = System.out;
if (LOCAL_TEST) {
in = new MyScanner("E:\\zin2.txt");
}
else {
boolean usingFileForIO = false;
if (usingFileForIO) {
in = new MyScanner("input.txt");
out = new PrintStream("output.txt");
}
else {
in = new MyScanner();
out = System.out;
}
}
solve();
}
private static void solve() throws IOException
{
int n = in.nextInt();
int m = in.nextInt();
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = in.nextInt();
}
}
int res = Integer.MAX_VALUE;
boolean[] isPrm = GetPrimeTable(200000);
int[] nextPrm = new int[200001];
int curPrm = 200000;
while (!isPrm[curPrm])
curPrm--;
for (int i = curPrm; i >= 1; i--) {
if (isPrm[i]) {
curPrm = i;
}
nextPrm[i] = curPrm;
}
for (int i = 0; i < n; i++) {
int step = 0;
for (int j = 0; j < m; j++) {
int num = a[i][j];
step += nextPrm[num] - num;
}
res = Math.min(res, step);
}
for (int j = 0; j < m; j++) {
int step = 0;
for (int i = 0; i < n; i++) {
int num = a[i][j];
step += nextPrm[num] - num;
}
res = Math.min(res, step);
}
out.println(res);
}
public static boolean[] GetPrimeTable(int maxNum) {
boolean[] isPrime = new boolean[maxNum + 1];
for (int i = 0; i < isPrime.length; i++) {
isPrime[i] = true;
}
isPrime[0] = isPrime[1] = false;
int sqrtMaxNum = (int) Math.sqrt(maxNum) + 1;
for (int i = 2; i <= sqrtMaxNum; i++) {
if (!isPrime[i])
continue;
int k = i * i;
while (k <= maxNum) {
isPrime[k] = false;
k += i;
}
}
return isPrime;
}
static class MyScanner {
Scanner inp = null;
public MyScanner() throws IOException
{
inp = new Scanner(System.in);
}
public MyScanner(String inputFile) throws IOException {
inp = new Scanner(new FileInputStream(inputFile));
}
public int nextInt() throws IOException {
return inp.nextInt();
}
public long nextLong() throws IOException {
return inp.nextLong();
}
public double nextDouble() throws IOException {
return inp.nextDouble();
}
public String nextString() throws IOException {
return inp.next();
}
}
} | JAVA |
271_B. 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
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. | 2 | 8 | import static java.lang.System.*;
import static java.lang.Math.*;
import java.math.*;
import java.util.*;
import java.io.*;
public class CodeForces {
public static void main(String[] args) {
boolean isPrime[]=new boolean[1000000];
isPrime[0]=true;
for(int i=1; i<1000000; i++){
if(isPrime[i-1]==false){
for(int j=2; j*i<1000000; j++){
isPrime[i*j-1]=true;
}
}
}
Scanner input=new Scanner(System.in);
int n=input.nextInt();
int m=input.nextInt();
int matrix[][]=new int[n][m];
int leastmoves=100000000;
for(int row=0; row<n; row++){
for(int col=0; col<m; col++){
matrix[row][col]=input.nextInt();
}
}
for(int row=0; row<n; row++){
int rowcounter=0;
for(int col=0; col<m; col++){
int counter=0;
while(isPrime[matrix[row][col]-1]!=false){
matrix[row][col]++;
counter++;
}
matrix[row][col]=counter;
rowcounter+=counter;
}
if(rowcounter<leastmoves){
leastmoves=rowcounter;
}
}
for(int col=0; col<m; col++){
int colcounter=0;
for(int row=0; row<n; row++){
colcounter+=matrix[row][col];
}
if(colcounter<leastmoves){
leastmoves=colcounter;
}
}
out.println(leastmoves);
}
}
| JAVA |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
vector<int> sv;
bool mrk[300000];
int grid[700][700];
void filla() {
for (int i = 2; i <= 200000; i++) {
if (!mrk[i]) {
sv.push_back(i);
for (int j = 2; j * i <= 200000; j++) mrk[j * i] = 1;
}
}
}
int main() {
filla();
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> grid[i][j];
}
}
long long ans = 1e15;
for (int i = 0; i < n; i++) {
long long cnt = 0;
for (int j = 0; j < m; j++) {
cnt += min(
abs(grid[i][j] - (*lower_bound(sv.begin(), sv.end(), grid[i][j]))),
abs(grid[i][j] - (*upper_bound(sv.begin(), sv.end(), grid[i][j]))));
}
ans = min(cnt, ans);
}
for (int i = 0; i < m; i++) {
long long cnt = 0;
for (int j = 0; j < n; j++) {
cnt += min(
abs(grid[j][i] - (*lower_bound(sv.begin(), sv.end(), grid[j][i]))),
abs(grid[j][i] - (*upper_bound(sv.begin(), sv.end(), grid[j][i]))));
}
ans = min(cnt, ans);
}
cout << ans << endl;
}
| CPP |
271_B. 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
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. | 2 | 8 |
import java.io.*;
import java.util.*;
public class CN167B {
static FastScanner in =new FastScanner(System.in);
static boolean isComposite[] = new boolean[1000001];
static int INF = Integer.MAX_VALUE/2;
public static void main (String args[]){
GharbalErnesten(1000000);
isComposite[1]=true;
isComposite[0]=true;
int n = in.nextInt();
int m = in.nextInt();
int a[][] = new int[n][m];
int b[][] = new int[n][m];
for(int i = 0 ; i < n ; i++){
for(int j = 0 ;j < m ; j++){
int t = in.nextInt();
a[i][j]= t ;
int c = 0;
while(isComposite[t]){
t++;
c++;
}
b[i][j]=c;
}
}
int min = INF;
for(int i = 0 ; i < n ;i++){
int c = 0;
for(int j = 0 ; j < m ; j++){
c+=b[i][j];
}
if(c<min)
min = c;
}
for(int j = 0 ; j < m ;j++){
int c = 0;
for(int i = 0 ; i < n ; i++){
c+=b[i][j];
}
if(c<min)
min = c;
}
System.out.println(min);
}
public static void GharbalErnesten(int upper) {
int upSqr = (int) Math.sqrt(upper); // Primes Are Is False
for (int m = 2; m <= upSqr; m++) {
if (!isComposite[m]) {
for (int k = m * m; k <= upper; k += m) {
isComposite[k] = true;
}
}
}
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
} | JAVA |
271_B. 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
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. | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
struct hash_pair {
template <class T1, class T2>
size_t operator()(const pair<T1, T2>& p) const {
auto hash1 = hash<T1>{}(p.first);
auto hash2 = hash<T2>{}(p.second);
return hash1 ^ hash2;
}
};
long long t;
vector<long long> v;
long long arr[1000005];
void seive() {
long long a, b, c, d, i, j;
for (i = 1; i <= 1e6; i++) {
arr[i] = i;
if (i % 2 == 0) arr[i] = 2;
}
for (i = 3; i * i < 1e6; i += 2) {
if (arr[i] != i) continue;
for (j = i * i; j <= 1e6; j += 2 * i) {
if (arr[j] == j) arr[j] = i;
}
}
for (i = 2; i <= 1e6; i++) {
if (arr[i] == i) v.push_back(i);
}
}
long long prime[505][505];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long a, b, c, d, e, f, g, i, j;
long long n, k;
seive();
cin >> a >> b;
for (i = 1; i <= a; i++) {
for (j = 1; j <= b; j++) {
cin >> d;
f = lower_bound(v.begin(), v.end(), d) - v.begin();
prime[i][j] = v[f] - d;
}
}
f = 0x3f3f3f3f;
for (i = 1; i <= a; i++) {
g = 0;
for (j = 1; j <= b; j++) {
g += prime[i][j];
}
f = min(g, f);
}
for (i = 1; i <= b; i++) {
g = 0;
for (j = 1; j <= a; j++) {
g += prime[j][i];
}
f = min(g, f);
}
cout << f << endl;
return 0;
}
| CPP |
271_B. 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
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. | 2 | 8 | import bisect
n, m = map(int, raw_input().split())
matrix = []
for i in xrange(n):
matrix.append(list(map(int, raw_input().split())))
primes = [i for i in xrange(101000)]
primes[0] = -1
primes[1] = -1
only_primes = []
for i in xrange(len(primes)):
if primes[i] != -1:
only_primes.append(primes[i])
for j in xrange(primes[i]*2, len(primes), primes[i]):
primes[j] = -1
for i in xrange(n):
for j in xrange(m):
next_prime_idx = bisect.bisect_left(only_primes, matrix[i][j])
matrix[i][j] = only_primes[next_prime_idx] - matrix[i][j]
min_ops = 99999999999
for row in matrix:
min_ops = min(min_ops, sum(row))
for j in xrange(m):
temp_sum = 0
for i in xrange(n):
temp_sum += matrix[i][j]
min_ops = min(min_ops, temp_sum)
print(min_ops)
| PYTHON |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.