1031: Find the law I
Time Limit: 1 Sec Memory Limit: 128 MBCommits: 417 Resolved: 180
[ Commit ][ Status ][ Discussion ]
Topic description
The old Chinese medicine doctor Bei Lei gave the big bread an n*m matrix, and the mysterious clothes that solve this matrix (add up and output each element of this matrix) will never fall to the bottom of the bed again (the big bread clothes something always falls to the bottom of the bed).
The old Chinese doctor gave some samples of the big bread, please help the big bread to find out the law and crack the mystery.
5 6
2 3 4 5 6 7
3 2 5 3 7 4
4 5 2 7 8 3
5 3 7 2 9 5
6 7 8 9 2 11
154
3 10
2 3 4 5 6 7 8 9 10 11
3 2 5 3 7 4 9 5 11 6
4 5 2 7 8 3 10 11 4 13
187
8 8
2 3 4 5 6 7 8 9
3 2 5 3 7 4 9 5
4 5 2 7 8 3 10 11
5 3 7 2 9 5 11 3
6 7 8 9 2 11 12 13
7 4 3 5 11 2 13 7
8 9 10 11 12 13 2 15
9 5 11 3 13 7 15 2
442
enter
Multiple sets of data
Each set of data contains one row, 2 numbers N, M, N represents the number of rows, M represents the number of columns (1 <= N, M <= 1000)
output
Output a row, the sum of all elements of the matrix
sample input
5 6
3 10
8 8
Sample output
154
187
442
Analysis: The problem of finding the greatest common divisor
At first glance, this question has no clue. It seems that there is no regularity between the rows and columns of the matrix. After searching on the Internet, I found that this regularity is really difficult to find.
Looking at the first row of each matrix, it is not difficult to find that it increases from 2 to 2+M-1. Take the second input as an example to observe the remaining rows:
j: 1 2 3 4 5 6 7 8 9 10
i= 2: 3 2 5 3 7 4 9 5 11 6
i+j: 4 4 5 6 7 8 9 10 11 12
i=3: 4 5 2 7 8 3 10 11 4 13
i+j: 4 5 6 7 8 9 10 11 12 13
and so on, it is not difficult to find that when i and j do not have the greatest common divisor, the corresponding value of the input matrix is (i+j), and when there is the greatest common divisor, the corresponding value of the input matrix is (i+j)/ i, the greatest common divisor of j.
The code is as follows:
#include<iostream>
using namespace std;
//The efficiency of tossing and dividing is high
int gcd(int a,int b){
if(b==0)
return a;
return gcd(b,a%b);
}
int main(){
int N,M,ans;
while(scanf("%d%d",&N,&M)!=EOF){
ans=0;
for(int i=1;i<=N;i++){
for(int j=1;j<=M ;j++){
ans+=(i+j)/gcd(i,j);
}
}
printf("%d\n",ans);
}
}
By the way, enter multiple sets of data while(scanf("%d %d",&N,&M)!=EOF), if EOF is not added, the time limit will be exceeded.