Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,236 questions

56,139 answers

573 users

How to write a function that calculates power in O(log(n)) time with C

1 Answer

0 votes
#include <stdio.h>

long power(long num, long n) {
    if (n == 0) {
        return 1;
    }

    if (n % 2 == 0) {
        return power(num * num, n / 2);
    } else {
        return num * power(num * num, n / 2);
    }
}

int main() {
    for (int i = 0; i < 15; i++) {
        printf("pow(%d, %d) = %ld\n", 2, i, power(2, i));
    }
}


        
/*
run:

pow(2, 0) = 1
pow(2, 1) = 2
pow(2, 2) = 4
pow(2, 3) = 8
pow(2, 4) = 16
pow(2, 5) = 32
pow(2, 6) = 64
pow(2, 7) = 128
pow(2, 8) = 256
pow(2, 9) = 512
pow(2, 10) = 1024
pow(2, 11) = 2048
pow(2, 12) = 4096
pow(2, 13) = 8192
pow(2, 14) = 16384
     
*/

 



answered Dec 14, 2024 by avibootz

Related questions

...