1.编写函数,判断两个整数是否互质,其中求两个正整数M、N的最大公约数使用辗转相除法
#include <stdio.h>
int prime(int m, int n) {
int temp;
while (n != 0) {
temp = m % n;
m = n;
n = temp;
}
if (m == 1)
return 1;
else
return 0;
}
int main() {
printf(prime(50, 2) ? "Yes" : "No");
return 0;
}
2.编程序,打印所有三位的Armstrong数,所谓Armstrong数是指其值等于它本身每位数字立方和的数。
#include <stdio.h>
int armstr(int n) {
int sum=0;
int flag=n;
while(n>0) {
sum+=pow(n%10,3);
n/=10;
}
if(flag==sum)
return 1;
return 0;
}
int main() {
printf("%d",armstr(152));
}
3.编写一个递归函数,实现在已递增排序的整数数组中进行二分检索
#include <stdio.h>
int search(int *a,int left,int right,int key) {
while(left<=right) {
int mid=(left+right)/2;
if(a[mid]==key)
return mid;
else if(a[mid]<key)
return (a,mid+1,right,key);
return(a,left,mid-1,key);
}
return -1;
}
4.一个整数可以表示成图一的形式(符号有两种可能:+,-)
①设计这种表示法的数据类型。②并编写函数判断任意给定两个整数的大小
#include <stdio.h>
#include <stdlib.h>
typedef struct List {
int sign;
int len;
struct node *next;
} List;
typedef struct node {
int key;
struct node *next;
} node;
int compare(struct List *a,struct List *b) {
if(a->sign==1&&b->sign==-1)
return 1;
if(a->sign==-1&&b->sign==1)
return -1;
if(a->sign==-1&&b->sign==-1) {
if(a->len>b->len)
return -1;
else if(a->len<b->len)
return 1;
}
if(a->sign==1&&b->sign==1) {
if(a->len<b->len)
return -1;
else if(a->len>b->len)
return 1;
}
struct node *p=a->next,*q=b->next;
while(p!=NULL&&q!=NULL) {
if(p->key>q->key) {
if(a->sign==-1&&b->sign==-1)
return -1;
if(a->sign==1&&b->sign==1)
return 1;
} else if(p->key<q->key) {
if(a->sign==-1&&b->sign==-1)
return 1;
if(a->sign==1&&b->sign==1)
return -1;
}
p=p->next;
q=q->next;
}
return 0;
}