Skip to content

Instantly share code, notes, and snippets.

@jatinsharrma
Last active March 31, 2019 14:41
Show Gist options
  • Save jatinsharrma/68f49d656b80b6c3c043a1b68d9120de to your computer and use it in GitHub Desktop.
Save jatinsharrma/68f49d656b80b6c3c043a1b68d9120de to your computer and use it in GitHub Desktop.
Power function using recursion
#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