Sum of natural numbers

//Time complexity O(n) and Space complexity O(n)
int sum_recursive(int n) {
    if(n == 0) {
        return 0;
    }
    return sum_recursive(n - 1) + n;
}

//Time complexity O(n) and Space complexity O(1)
int sum_iterative(int n) {
    int sum = 0;
    for(int i = 1; i <= n; i++) {
        sum += i;
    }
    return sum;
}
    
//Time complexity O(1) and Space complexity O(1)
int sum_usingFormula(int n) {
    return n * (n + 1) / 2;
}

Comments

Popular posts from this blog

SQL basic interview question

gsutil Vs Storage Transfer Service Vs Transfer Appliance