一直是compile error
你写的prime(int n)函数里的i值貌似没有初始值,而且拿它直接与形参n进行了(i%n)的运算,没有理由啊。。所以i在这个函数中没有任何作用。5楼的可以通过编译运行处结果。。
分2段找,从n往前找到最接近的素数,从后找到最接近的素数,注意1不是素数的情况,还要注意n本身是不是素数 代码如下:测试了2次都AC了 #include<stdio.h> #include<math.h> int main() { int i, j, k, m, n, a, b, d, t; scanf("%d", &m); while(m--) { scanf("%d", &n); if(n == 1) printf("2 1\n"); else { for(i = n - 1; i >= 2; i--) { t = 1; for(j = 2; j <= sqrt(i); j++) { if(i % j == 0) { t = 0; break; } } if(t)break; } a = i; for(i = n + 1; i; i++) { t = 1; for(j = 2; j <= sqrt(i); j++) { if(i % j == 0) { t = 0; break; } } if(t) break; } b = i; t = 1; k = (n - a) <= (b - n) ? a : b; d = (n - a) <= (b - n) ? (n - a) : (b - n); for(i = 2; i <= sqrt(n); i++) if(n % i == 0) { t = 0; break; } printf("%d %d\n", t > 0 ? n : k, t > 0 ? 0 : d); } } return 0; }
#include <stdio.h> #include <math.h> int larger_prime(int num) { int i, j; i = num + 1; while(i<num*2) { for(j=2; j<i; j++) { if(i%j==0) break; } if(j==i) return i; i++; } return i; } int smaller_prime(int num) { int i, j; for(i=num; i>1; i--) { for(j=2; j<i; j++) { if(i%j==0) break; } if(j==i) return i; } } void output_prime(int num) { int smaller, larger; if(num < 2) { printf("illagal num:%d\n", num); return ; } smaller = smaller_prime(num); if(smaller == num) { printf("%d %d\n", num, 0); } else { larger = larger_prime(num); if(larger-num < num-smaller) printf("%d %d\n", larger, larger-num); else printf("%d %d\n", smaller, num-smaller); } } int main() { int count; printf("Please input the count of numbers:"); scanf("%d", &count); int num[count]; int i; for(i=0; i<count; i++) { printf("Please input the No.%d number(>1):", i+1); scanf("%d", &num[i]); } printf("Output...\n"); for(i=0; i<count; i++) output_prime(num[i]); printf("\n"); return 0; }
#include <math.h> #include <stdio.h> #define ALL 78499 void Init(int ss[]) { int i, j, k = 8, temp; for (i = 23;k != ALL;i += 2) { temp = (int)sqrt(i); for (j = 0;ss[j] <= temp;++j) { if (i % ss[j]) continue; break; } if (ss[j] <= temp) continue; ss[k++] = i; } } int find(int s[], int key, int beg, int end) { int ip = (beg + end) / 2; if (s[ip] == key) return ip; if (ip == beg) return (s[ip]+s[ip+1]-key-key) < 0 ? ip+1 : ip; if (s[ip] > key) return find(s, key, beg, ip); else return find(s, key, ip, end); } int main() { int tmp, ip, m, n, s[ALL] = {2, 3, 5, 7, 11, 13, 17, 19}; Init(s); scanf("%d", &m); while (m--) { scanf("%d", &n); ip = find(s, n, 0, ALL-1); if ((tmp = n - s[ip]) < 0) tmp = -tmp; printf("%d %d\n", s[ip], tmp); } return 0; }