当前位置:网站首页>Example of time complexity calculation

Example of time complexity calculation

2022-04-23 15:07:00 White horse is not a horse·

subject :x Of n Power , Results output

package demo4_8;

public class leijia {
    
    static int temp;
    public static void main(String[] args) {
    
        // Think about the time complexity of recursion 
        // problem :x Of n Power 
        int x=2;
        int n=8;
        System.out.println(" Method 1 :"+method1(x,n));
        System.out.println(" Method 2 :"+method2(x,n));
        System.out.println(" Method 3 :"+method3(x,n));
        System.out.println(" Method four :"+method4(x,n));
    }

    // Method 1 : Solve directly ( The time complexity is O(n)
    public static int method1(int x,int n){
    
        int result=1;
        for(int i=0;i<n;i++){
    
            result*=x;
        }
        return result;
    }

    // Method 2 : Recursive method : Time complexity or O(n)
    public static int method2(int x,int n){
    
        if(n==0) return 1;
        return method2(x,n-1)*x;
    }
    // Method 3 : Recursive method : Time complexity or O(n)
    // Calculate through full binary tree , Time complexity or O(n)
    public static int method3(int x,int n){
    
        if(n==0) return 1;
        if(n%2==1) return method3(x,n/2)*method3(x,n/2)*x;
        return method3(x,n/2)*method3(x,n/2);
    }

    // Method four : Recursive method : Time complexity or O(n)
    public static int method4(int x,int n){
    
        if(n==0) return 1;
        temp=method4(x,n/2); // Record intermediate variables 
        System.out.println(" frequency ");
        if(n%2==1) return temp*temp*x;
        return temp*temp;
    }
}

版权声明
本文为[White horse is not a horse·]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231407525452.html