What is the C++ function to raise a number to a power?
pow() in the cmath library. More info here.
Don't forget to put #include<cmath>
at the top of the file.
To the power of in C?
You need pow();
function from math.h
header.
syntax
#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);
Here x is base and y is exponent. result is x^y
.
usage
pow(2,4);
result is 2^4 = 16. //this is math notation only
// In c ^ is a bitwise operator
And make sure you include math.h
to avoid warning ("incompatible implicit declaration of built in function 'pow'
").
Link math library by using -lm
while compiling. This is dependent on Your environment.
For example if you use Windows it's not required to do so, but it is in UNIX based systems.
The most efficient way to implement an integer based power function pow(int, int)
Exponentiation by squaring.
int ipow(int base, int exp)
{
int result = 1;
for (;;)
{
if (exp & 1)
result *= base;
exp >>= 1;
if (!exp)
break;
base *= base;
}
return result;
}
This is the standard method for doing modular exponentiation for huge numbers in asymmetric cryptography.
Integer power in c
I'm pretty sure you mean:
y = pow(x, n);
~~
You're getting a "weird" result because y
is never initialized to anything; you are raising x
to the power of (some garbage) and getting garbage out.
Note that, as @0A0D suggests in a comment, if you were to use more descriptive variables, this problem would be much more obvious:
int base = 0;
int exponent = 0;
long int result;
printf("Enter the base and exponent, on separate lines\n");
scanf("%i\n%i\n", &base, &exponent);
result = pow(base, result);
~~~~~~~ oops!
Also, as @icepack has mentioned, since y
is a long int
, the format should be %li
(not %i
):
printf("%li\n", y);
How do you do exponentiation in C?
use the pow
function (it takes float
s/double
s though).
man pow
:
#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);
EDIT: For the special case of positive integer powers of 2
, you can use bit shifting: (1 << x)
will equal 2
to the power x
. There are some potential gotchas with this, but generally, it would be correct.
What is the correct way to raise an integer to a positive integer power in C++?
The standard, fast exponentiation uses repeated squaring:
uint_t power(uint_t base, uint_t exponent)
{
uint_t result = 1;
for (uint_t term = base; exponent != 0; term = term * term)
{
if (exponent % 2 != 0) { result *= term; }
exponent /= 2;
}
return result;
}
The number of steps is logarithmic in the value of exponent
. This algorithm can trivially be extended to modular exponentiation.
Update: Here is a modified version of the algorithm that performs one less multiplication and handles a few trivial cases more efficiently. Moreover, if you know that the exponent is never zero and the base never zero or one, you could even remove the initial checks:
uint_t power_modified(uint_t base, uint_t exponent)
{
if (exponent == 0) { return 1; }
if (base < 2) { return base; }
uint_t result = 1;
for (uint_t term = base; ; term = term * term)
{
if (exponent % 2 != 0) { result *= term; }
exponent /= 2;
if (exponent == 0) { break; }
}
return result;
}
how could I use the power function in c/c++ without pow(), functions, or recursion
It is a series. Replace pow()
based on the previous iteration. @Bathsheba
Code does not need to call pow()
. It can form pow(x, 5 * i - 1)
and pow(-1, i - 1)
, since both have an int
exponent based on the iterator i
, from the prior loop iteration.
Example:
Let f(x, i) = pow(x, 5 * i - 1)
Then f(x, 1) = x*x*x*x
and f(x, i > 1) = f(x, i-1) * x*x*x*x*x
double power_n1 = 1.0;
double power_x5 = x*x*x*x;
for (int i = 1; i < j + 1; i++)
// sum += (pow(-1, i - 1)) / (5 * i - 1) * (pow(x, 5 * i - 1));
sum += power_n1 / (5 * i - 1) * power_x5;
power_n1 = -power_n1;
power_x5 *= x*x*x*x*x;
}
Does pow() work for int data type in C?
Floating point precision is doing its job here. The actual working of pow
is using log
pow(a, 2) ==> exp(log(a) * 2)
Look at math.h
library which says:
###<math.h>
/* Excess precision when using a 64-bit mantissa for FPU math ops can
cause unexpected results with some of the MSVCRT math functions. For
example, unless the function return value is stored (truncating to
53-bit mantissa), calls to pow with both x and y as integral values
sometimes produce a non-integral result. ... */
Just add 0.5
to the return value of pow
and then convert it to int
.
b = (int)(pow(a,2) + 0.5);
So, the answer to your question
Does pow() work for
int
data type in C?
Not always. For integer exponentiation you could implement your own function (this will work for 0 and +ve exp
only):
unsigned uint_pow(unsigned base, unsigned exp)
{
unsigned result = 1;
while (exp)
{
if (exp % 2)
result *= base;
exp /= 2;
base *= base;
}
return result;
}
Related Topics
Why Can't I Open Avi Video in Opencv
How to (Un)Escape Strings in C/C++
How to Fix .Pch File Missing on Build
How to Implement a BéZier Curve in C++
Conventions for Accessor Methods (Getters and Setters) in C++
Why Is 'Std::Initializer_List' Often Passed by Value
Is It Safe to Realloc Memory Allocated with New
Converting Yuv into Bgr or Rgb in Opencv
Avoiding Denormal Values in C++
Why Do Some Experienced Programmers Write Comparisons with the Value Before the Variable
How to Have Two Functions That Call Each Other C++
How to Use Sort() in C++ with Custom Sort Member Function
Differencebetween Exit() and Abort()
Can Const-Correctness Improve Performance
Why am I Getting String Does Not Name a Type Error
Obtain a Std::Ostream Either from Std::Cout or Std::Ofstream(File)