11

Click here to load reader

Write a C Program to Calculate Pow(x,n) _ GeeksforGeeks

Embed Size (px)

Citation preview

Page 1: Write a C Program to Calculate Pow(x,n) _ GeeksforGeeks

5/12/12 Write a C program to calculate pow(x,n) | GeeksforGeeks

1/11www.geeksforgeeks.org/archives/28

GeeksforGeeks

A computer science portal for geeks

HomeQ&AInterview CornerAsk a question

FeedbackContributeAbout us

SubscribeArraysArticlesBit MagicC/C++ PuzzlesGFactsLinked ListsMCQMiscOutputStringsTrees

Write a C program to calculate pow(x,n)

March 22, 2009

Below solution divides the problem into subproblems of size y/2 and call thesubproblems recursively.

#include<stdio.h> /* Function to calculate x raised to the power y */int power(int x, unsigned int y){ if( y == 0) return 1; else if (y%2 == 0) return power(x, y/2)*power(x, y/2);

Page 2: Write a C Program to Calculate Pow(x,n) _ GeeksforGeeks

5/12/12 Write a C program to calculate pow(x,n) | GeeksforGeeks

2/11www.geeksforgeeks.org/archives/28

Time Complexity: O(n)Space Complexity: O(1)Algorithmic Paradigm: Divide and conquer.

Above function can be optimized to O(logn) by calculating power(x, y/2) only once andstoring it.

Time Complexity of optimized solution: O(logn)Let us extend the pow function to work for negative y and float x.

else return x*power(x, y/2)*power(x, y/2); } /* Program to test function power */int main(){ int x = 2; unsigned int y = 3; printf("%d", power(x, y)); getchar(); return 0;}

/* Function to calculate x raised to the power y in O(logn)*/int power(int x, unsigned int y){ int temp; if( y == 0) return 1; temp = power(x, y/2); if (y%2 == 0) return temp*temp; else return x*temp*temp;}

/* Extended version of power function that can work for float x and negative y*/#include<stdio.h> float power(float x, int y){ float temp; if( y == 0) return 1;

Page 3: Write a C Program to Calculate Pow(x,n) _ GeeksforGeeks

5/12/12 Write a C program to calculate pow(x,n) | GeeksforGeeks

3/11www.geeksforgeeks.org/archives/28

No related posts.

12 comments so far

1. Anuj says:February 5, 2011 at 12:58 PM

temp = power(x, y/2); if (y%2 == 0) return temp*temp; else { if(y > 0) return x*temp*temp; else return (temp*temp)/x; }} /* Program to test function power */int main(){ float x = 2; int y = -3; printf("%f", power(x, y)); getchar(); return 0;}

Send 6people

#include<stdio.h>main(){ int num, p , result; printf("Enter the number : "); scanf("%d",&num); printf("\nAnd its power also. : "); scanf("%d",&p);

Page 4: Write a C Program to Calculate Pow(x,n) _ GeeksforGeeks

5/12/12 Write a C program to calculate pow(x,n) | GeeksforGeeks

4/11www.geeksforgeeks.org/archives/28

ReplyAnuj says:February 5, 2011 at 12:59 PM

I think it's pretty simple

ReplyKK123 says:July 6, 2011 at 12:32 PM

Dude!! Din u notice time complexity??

ReplyAnuj says:July 6, 2011 at 3:30 PM

i didn't. u tell me

ReplyKK123 says:July 6, 2011 at 7:38 PM

ur algo takes O(n) whereas the one in article is O(logn)...

2. Raj says:January 11, 2011 at 4:09 PM

How to calculate power(float x, float y) ?

result = power(num,p); printf("\nThe result is %d\n", result);}power(int x, int y){ int i,temp =1; if(y==0) return(1); if(y==1) return(x); else { for(i=1;i<=y;i++) temp = temp*x; return(temp); }}

Page 5: Write a C Program to Calculate Pow(x,n) _ GeeksforGeeks

5/12/12 Write a C program to calculate pow(x,n) | GeeksforGeeks

5/11www.geeksforgeeks.org/archives/28

Reply3. Snehal Masne says:

December 20, 2010 at 7:44 PM

Thanks for the code.. interesting..

Reply4. Venki says:

August 27, 2010 at 11:54 PM

// Similar function, but depends on set bits// in the exponent (no recursion - logN)int power(int x, unsigned n) { // Holds next power // Will be used if next bit is set (odd) int intermediateProduct = x; // Final result int result = 1; // Repeat this till we iterate all the set bits while(n) { // Effectively equvalent to n%2 if (n & 1) { // If n is odd // power(a, b) = a * power(a, b/2) * power(a, b/2) // Note that next two terms are picked in the down statement result = intermediateProduct * result; } // Make up next bit n >>= 1; // Make the multiplication for next bit // Contributes for multiplication when n is even // power(a, b) = power(a, b/2) * power(a, b/2) intermediateProduct = intermediateProduct * intermediateProduct; } // Done! Return. return result;} // Drivervoid main(){

Page 6: Write a C Program to Calculate Pow(x,n) _ GeeksforGeeks

5/12/12 Write a C program to calculate pow(x,n) | GeeksforGeeks

6/11www.geeksforgeeks.org/archives/28

Reply5. Prabhakar says:

August 17, 2010 at 2:03 AM

we have to calculate x^n;

Time Complexity=O(log(n))

Replycodegeek says:August 27, 2010 at 6:31 PM

whyif (n&&1)its same asif (n)

what is initial value of y here??

ReplyPrabhakar says:August 27, 2010 at 7:08 PM

@codegeeks

sorry. It is (n&1) not (n&&1).

here intialise x=1,y=n;

Replynikhil says:September 2, 2010 at 6:43 PM

@PrabhakarIn the above initialisation we are not using value of anywhere in the

printf("%d\n", power(2, 5));}

int n;while(n){if(n&&1)x=x*y;y=y*y;n=n>>1;}

Page 7: Write a C Program to Calculate Pow(x,n) _ GeeksforGeeks

5/12/12 Write a C program to calculate pow(x,n) | GeeksforGeeks

7/11www.geeksforgeeks.org/archives/28

expression x^n. since x=1 and y=n and n=n . so how value of x willbe used.I hope u understand my question.

Reply

Comment

Name (Required) Email (Required)

Website URI Your Comment (Writing code? please paste your

code between sourcecode tags)

[sourcecode language="C"]/* Paste your code here (You may delete these lines if not writing code) */[/sourcecode]

Have Your Say

Pingbacks/Trackbacks

1. Program for Fibonacci numbers | GeeksforGeeks

Search

Popular Tags

GATEJavaDynamic ProgrammingBacktrackingPattern SearchingDivide & ConquerGraph

Page 8: Write a C Program to Calculate Pow(x,n) _ GeeksforGeeks

5/12/12 Write a C program to calculate pow(x,n) | GeeksforGeeks

8/11www.geeksforgeeks.org/archives/28

Operating SystemsRecursion

Popular Posts

All permutations of a given stringMemory Layout of C ProgramsUnderstanding “extern” keyword in CMedian of two sorted arraysTree traversal without recursion and without stack!Structure Member Alignment, Padding and Data PackingIntersection point of two Linked ListsLowest Common Ancestor in a BST.Check if a binary tree is BST or notSorted Linked List to Balanced BST

Page 9: Write a C Program to Calculate Pow(x,n) _ GeeksforGeeks

5/12/12 Write a C program to calculate pow(x,n) | GeeksforGeeks

9/11www.geeksforgeeks.org/archives/28

250 Subscribe

Forum Latest Discussion

LIS in nlogn timeLast Post By: kartik

Inside: Interview Questions

tree to fileLast Post By: Dheeraj

Inside: Interview Questions

Page 10: Write a C Program to Calculate Pow(x,n) _ GeeksforGeeks

5/12/12 Write a C program to calculate pow(x,n) | GeeksforGeeks

10/11www.geeksforgeeks.org/archives/28

Count internal nodes in a binary treeLast Post By: kartik

Inside: Interview Questions

Ancestor of two given leaf nodesLast Post By: dead

Inside: Trees specific questions

combine elements of an array, so as to minimize weights.Last Post By: rohanag

Inside: Interview Questions

FB interview questionLast Post By: ranganath111

Inside: Interview Questions

Testing of factorial of a numberLast Post By: rukawa

Inside: Interview Questions

numeric puzzleLast Post By: asm

Inside: Algorithms

Forum Categories

Interview QuestionsC/C++ Programming QuestionsAlgorithmsTrees specific questionsLinked List specific questionsMultiple Choice QuestionsObject oriented queriesGPuzzles

Page 11: Write a C Program to Calculate Pow(x,n) _ GeeksforGeeks

5/12/12 Write a C program to calculate pow(x,n) | GeeksforGeeks

11/11www.geeksforgeeks.org/archives/28

Operating SystemsMiscellaneousJava specific QuestionsPerl specific Questions

Recent Comments

Venki on Structure Member Alignment, Padding and Data Packingavi on Structure Member Alignment, Padding and Data Packingatul on A Program to check if strings are rotations of each other or notVenki on Structure Member Alignment, Padding and Data Packingrahul on Dynamic Programming | Set 13 (Cutting a Rod)Sandeep on Dynamic Programming | Set 3 (Longest Increasing Subsequence)Yueming on Dynamic Programming | Set 3 (Longest Increasing Subsequence)avi on Structure Member Alignment, Padding and Data Packing

@geeksforgeeks, Some rights reservedPowered by WordPress & MooTools, customized by geeksforgeeks team