今天贴三个小程序,程序很小,但是希望这些小东西都能记在心里
1.求多项式
1 package 多项式; 2 3 public class Polynomial { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 int[] xishu = new int[]{2,1,0,8,4}; 8 System.out.println(poly(xishu,3)); 9 10 } 11 private static long poly(int[] xishu,int x){ 12 long po = 0L; 13 for(int i = xishu.length-1;i>=0;i--){ 14 po=po*x+xishu[i];//注意系数是从an开始递减到a1的 15 } 16 return po; 17 } 18 19 }
2.判断一个数是否为素数
1 package 判断素数; 2 3 public class PrimeNumber { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 System.out.println(isPrime(71)); 8 } 9 10 private static boolean isPrime(int a) { 11 if(a<2){ 12 return false; 13 } 14 else{ 15 for(int i=2;i<Math.sqrt(a);i++){ 16 if(a%i==0) 17 return false; 18 } 19 } 20 return true; 21 } 22 23 }
3. 二分查找
时间复杂度为o(logN)
1 package binarySearch; 2 //折半查找必须针对已排序的数列 3 public class BinarySearch { 4 5 static int NOT_FOUND = -1; 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 int[] aa = new int[]{2,3,7,89,100,256,445,789}; 9 System.out.println(binarySearch(aa,100)); 10 } 11 private static int binarySearch(int[] sortedArray ,int find){ 12 int low =0; 13 int high = sortedArray.length-1; 14 while(low<=high){ 15 int mid = (low+high)/2; 16 if(sortedArray[mid]<find){ 17 low=mid+1; 18 } 19 else if(sortedArray[mid]>find){ 20 high=mid-1; 21 } 22 else 23 return mid; 24 } 25 return NOT_FOUND; 26 } 27 28 }
时间: 2024-11-05 05:00:45