幂运算
package cn.edut.test_algorithm;
public class Demo_PowerOperation {
public static void main(String[] args) {
System.out.println(pow_bad(2,10));
System.out.println(pow(2,10));
}
public static long pow(long x , int n) {
if(n==0) {
return 1 ;
}
if(n==1) {
return x ;
}
if(n%2==0) {
return pow(x*x , n/2);
}else {
return pow(x*x, n/2)*x ;
}
}
public static long pow_bad(long x , int n) {
return n-->1 ? pow_bad(x, n)*x : x;
}
}
欧几里得算法
package cn.edut.test_algorithm;
public class Demo_EuclidAlgorithm {
public static void main(String[] args) {
System.out.println(myGcd(1989,1590));
System.out.println(gcd(1989,1590));
}
public static Integer gcd(Integer Max, Integer Min) {
return Max%Min==0 ? Min : gcd(Min,Max%Min) ;
}
public static Long gcd(Long Max, Long Min) {
return Max%Min==0 ? Min : gcd(Min,Max%Min) ;
}
public static int myGcd(int N,int M) {
int out =1 ;
int min = Integer.min(N, M);
for(int i=1 ;i<=min ; i++)
{
if(N%i==0 && M%i==0) {
out = i;
}
}
return out ;
}
}
折半查找(太废了,懒得写)