几个简单的小算法
程序代码:
//若大家手中有一些算法的话,不妨一起贴出来,大家往后看的时候也方便 /// <summary> /// 折半查找 /// </summary> /// <param name="arr">一维数组</param> /// <param name="num">查找的数字</param> /// <returns>对应数字的索引(数组中相同数字返回第一个的索引),若不存在则值为-1</returns> public static int FindInHalf(int[] arr,int num) { int hight = arr.Length - 1, low = 0; int index = -1; while (low <= hight) { int middle = (hight + low) / 2; if (num == arr[middle]) { index = middle; break; } else { if (num < arr[middle]) hight = middle - 1; else low = middle + 1; } } return index; } /// <summary> /// 反转字符串 /// </summary> /// <param name="str"></param> /// <returns></returns> private static string RetStrBind(string str) { string result = ""; for (int i = str.Length - 1; i >= 0; i--) { result += str[i]; } return result; } /// <summary> /// 求一个整数是否是质数 /// </summary> /// <param name="num"></param> /// <returns>true为否,fase为是</returns> private static bool GetPrime(int num) { bool rebool = false; for (int i = 2; i < num; i++) { rebool = num % i == 0; if (rebool) { break; } } return rebool; } /// <summary> /// 求两个整数的最小公倍数 /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns>最小公倍数</returns> public static int GetMultiple(int a, int b) { int mul=0; for (int i = (a > b) ? a : b; i <= a * b; i++) { if (i % a == 0 && i % b == 0) { mul = i; break; } } return mul; } /// <summary> /// 求两个整数的最大公约数 /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns>最大公约数</returns> public static int GetDivisor(int a, int b) { int div = 0; for (int i = (a < b) ? a :b; i >= 1; i--) { if (a % i == 0 && b % i == 0) { div = i; break; } } return div; }