Last active
March 31, 2019 14:41
-
-
Save jatinsharrma/68f49d656b80b6c3c043a1b68d9120de to your computer and use it in GitHub Desktop.
Power function using recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
int power(int a, int b){ | |
if (b == 1){ | |
return(a); | |
} | |
else{ | |
return (a * power(a,b-1)); | |
} | |
} | |
void main(){ | |
int a=2, b=10; | |
a = power(a,b); | |
printf("%d",a); | |
} | |
------------------------------------------- | |
// Efficient way less multiplications | |
#include <stdio.h> | |
int power(int a, int b){ | |
int p; | |
if (b == 1){ | |
return a; | |
} | |
p = power(a,b/2); | |
if (b%2==1){ | |
return p*p*a; | |
} | |
else{ | |
return p*p; | |
} | |
} | |
void main(){ | |
int a=2, b=10; | |
a = power(a,b); | |
printf("%d",a); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment