组合数公式,含阶乘(nCr):
int Jc(int n) { int result=1; int i; for(i=1;i<=n;i++) result*=i; return result; } int Ncr(int n,int r) { return Jc(n)/(Jc(r)*Jc(n-r)); }
整数转为字符数组:
int Convert(int n,char *c) { int i=0; while(n) { c[i++]=n%10; n/=10; } return i; //位数 }
交换两个字符:
void Switch(char *a,char *b) { char t; t=*a; *a=*b; *b=t; }
斐波那契数列(递归):
int Fibonacci(int n) { if(n==1||n==2) return 1; if(n>2) return Fibonacci(n-1)+Fibonacci(n-2); }
最大公约数:
int MaxGY(int a,int b) { int k=a<b? a:b; while(a%k!=0||b%k!=0) k--; return k; }
最小公倍数:
int MinGB(int a,int b) { int k=a>b? a:b; while(k%a!=0||k%b!=0) k++; return k; }
判断n是否为素数:
int Sushu(int n) { if(n==1||n==0) return 0; int a; for(a=2;a<n;a++) { if(n%a==0) return 0; } return 1; }
判断闰年:
int Runnian(int n) { if((n%4 == 0&&n%100 != 0)||(n%400 == 0)) return 1; else return 0; }
字符串匹配(返回串t在串s中的下标,如果不匹配则返回-1)
int StrIndex(char *s,char *t) { int ls,lt,i,j,flag; ls=strlen(s); lt=strlen(t); for(i=0;i<=ls-lt;i++) { flag=1; for(j=0;j<=lt;j++) { if(s[i+j]!=t[j]) { flag=0; break; } } if(flag==1) return i; } return -1; }
快速排序(无优化)
void QSort(int *l,int low,int high) { int Partition(int *l,int low,int high) { int pivotkey,t; pivotkey=l[low]; while(low<high) { while(low<high&&l[high]>=pivotkey) high--; t=l[low],l[low]=l[high],l[high]=t; while(low<high&&l[low]<=pivotkey) low++; t=l[low],l[low]=l[high],l[high]=t; } return low; } int pivot; if(low<high) { pivot=Partition(l,low,high); QSort(l,low,pivot-1); QSort(l,pivot+1,high); } }
二分查找(查找失败返回-1)
int BinarySearch(int *l,int n,int key) { int low,high,mid; low=0; high=n; while(low<high) { mid=(low+high)/2; if(key<l[mid]) high=mid-1; else if(key>l[mid]) low=mid+1; else return mid; } return -1; }