利用上面的prime函数,验证哥德巴赫猜想的程序代码如下: #include "math.h" int prime(int m) { int i,k; k=sqrt(m); for(i=2;i<k;i++) if(m%i==0) break; if(i>=k) return 1; else return 0; }
main() { int x,i; printf("please input a even number(>=6):\n"); scanf("%d",&x); if (x<6||x%2!=0) printf("dataerror!\n"); else for(i=2;i<=x/2;i++) if (prime(i)&&prime(x-i)) { printf("%d+%d\n",i,x-i); printf("验证成功!"); break; } }
基本思想:一列数放在数组a[1]---a[n]中,待查找的数放在x 中,把x与a数组中的元素从头到尾一一进行比较查找。用变量p表示a数组元素下标,p初值为1,使x与a[p]比较,如果x不等于a[p],则使p=p+1,不断重复这个过程;一旦x等于a[p]则退出循环;另外,如果p大于数组长度,循环也应该停止。(这个过程可由下语句实现) void main() { int a[10],p,x,i; printf("please input the array:\n"); for(i=0;i<10;i++) scanf("%d",&a); printf("please input the number you want find:\n"); scanf("%d",&x); printf("\n"); p=0; while(x!=a[p]&&p<10) p++; if(p>=10) printf("the number is not found!\n"); else printf("the number is found the no%d!\n",p); }
思考:将上面程序改写一查找函数Find,若找到则返回下标值,找不到返回-1
②基本思想:一列数放在数组a[1]---a[n]中,待查找的关键值为key,把key与a数组中的元素从头到尾一一进行比较查找,若相同,查找成功,若找不到,则查找失败。(查找子过程如下。index:存放找到元素的下标。) void main() { int a[10],index,x,i; printf("please input the array:\n"); for(i=0;i<10;i++) scanf("%d",&a); printf("please input the number you want find:\n"); scanf("%d",&x); printf("\n"); index=-1; for(i=0;i<10;i++) if(x==a) { index=i; break; } if(index==-1) printf("the number is not found!\n"); else printf("the number is found the no%d!\n",index); }
将上面的算法写成如下程序: void main() { int a[10],mid,bot,top,x,i,find; printf("please input the array:\n"); for(i=0;i<10;i++) scanf("%d",&a); printf("please input the number you want find:\n"); scanf("%d",&x); printf("\n"); bot=0;top=9;find=0; while(bot<top&&find==0) { mid=(top+bot)/2; if(x==a[mid]) {find=1;break;} else if(x<a[mid]) top=mid-1; else bot=mid+1; } if (find==1) printf("the number is found the no%d!\n",mid); else printf("the number is not found!\n"); }