对于判断一个数是不是素数,我们不需要从2遍历到n依次判断是否可以被整除。而只需从2测试到不比 sqrt(n)(对 n 开根号)大的整数即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<stdio.h> #include<math.h>
booljude(int x){ if (x <= 1) returnfalse;//若小于1,必不是素数 int bound = (int)sqrt(x) + 1;//枚举上界,愿多枚举一个数也不能少枚举一个数 for (int i = 0; i < bound; i++) if (x%i==0)//若能除尽,必不是素数 returnfalse; returntrue;//否则,是素数 } intmain(){ int n; while (scanf("%d",&n)!=EOF) puts(jude(n) ? "yes" : "no"); return0; }
#include<stdio.h> #include<math.h> #include<algorithm> usingnamespacestd; structResult//结果结构 { int diff; int x; int y; booloperator < (const Result& b) const { //利用C++算符重载直接定义小于运算符 return diff < b.diff; } }results[100]; int Matrix1[101][101]; int Matrix2[101][101]; intmain() { int N, M, n, m; int cnt = 0;//计数器 scanf("%d%d", &N, &M); for (int i = 1; i <= N; i++)//给大矩阵赋值 for (int j = 1; j <= M; j++) scanf("%d", &Matrix1[i][j]); scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++)//给小矩阵赋值 for (int j = 1; j <= m; j++) scanf("%d", &Matrix2[i][j]); for (int i = 1; i <= M - m + 1; i++)//开始暴力遍历两个矩阵,求其差绝对值的和 { for (int j = 1; j <= N - n + 1; j++) { int temp = 0; for (int k = 0; k < n; k++) for (int h = 0; h < m; h++) temp += abs(Matrix1[i + k][j + h] - Matrix2[k + 1][h + 1]);//累加此种情况差绝对值的和 results[cnt].diff = temp; results[cnt].x = i; results[cnt].y = j; cnt++; } } sort(results, results + cnt); printf("%d (%d,%d)\n", results[0].diff, results[0].x, results[0].y); }