C program to find nth power of integer m without pow().
Input:
m=3 n=2
output:
9.000
Tests to validate the program works as expected!
- For negative M
Input : -2 3
output : -8.000
- For negative N
Input : 2 -3
output : 0.125000
- For negative M and N
Input : -2 -3
output : -0.125000
However I am not getting the desired output
void main()
{
signed int m, n;
int i;
float p;
clrscr();
printf("Enter the number and its power (exponent)\n");
scanf("%d%d",&m,&n);
p=1;
if (n==0)
{
printf("%d raised to %d is: %f",m,n,p);
}
if (n>0)
{
for( i = 0 ; i < n ; i++ )
p*=m;
if(m>0)
printf("%d raised to %d is: %f",m,n,p);
if(m<0)
printf("%d raised to %d is: %f",m,n,-p);
}
if (n<0)
{
n=-n;
for( i = 0 ; i < n ; i++ )
p*=m;
if(m>0)
printf("%d raised to %d is: %f",m,-n,1/p);
if(m<0)
printf("%d raised to %d is: %f",m,-n,-(1/p));
}
getch();
}
Can u kindly provide the correct program for the test cases?
I can't declare signed float
as it is giving an error.
The code for negatives is incorrect. You cannot just blindly negate the result when the base m
is negative.
, but . Also, you're not printing anything if m
is zero!
And int
s are signed by default so signed int
is noise. float
s are signed too; but here you could as well use a double
for more precision. The return value of main
should be int
.
Therefore the fixed code would be (add nonstandard clrscr
s and getch
s to your taste ;):
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m, n, i;
double p = 1.0;
printf("Enter the number and its power (exponent)\n");
scanf("%d%d",&m,&n);
if (n==0) {
printf("%d raised to %d is: %f",m,n,p);
}
else if (n > 0) {
for(i = 0; i < n; i++)
p*=m;
printf("%d raised to %d is: %f",m,n,p);
}
else { // n < 0
n = -n;
for (i = 0 ; i < n ; i++)
p*=m;
printf("%d raised to %d is: %f", m, -n, 1 / p);
}
}
Try changing:
void main()
{
signed int m, n;
int i;
float p;
printf("Enter the number and its power (exponent)\n");
scanf("%d%d",&m,&n);
p=1;
if (n==0)
{
printf("%d raised to %d is: %f",m,n,p);
}
if (n>0)
{
for( i = 0 ; i < n ; i++ )
p*=m;
printf("%d raised to %d is: %f",m,n,p);
}
if (n<0)
{
n=-n;
for( i = 0 ; i < n ; i++ ){
p*=m;
}
printf("%d raised to %d is: %f",m,-n,1/p);
}
}
@Antti Haapala well identified the errors in OP's code.
As an interview question relating to pow()
substitute, certainly a solution that takes log2 N steps (as below) is preferable to one that takes N steps (OP's approach) where N is the exponent.
The key is to square the base on each iteration.
Using log2 N steps rather than N results in less error in the least significant digits.
With a negative exponent, simple invert the base.
Use double
to provide to provide at least 10, typically 17, decimal digits of precision.
double powdii(int x, int y) {
double z = 1.0;
double base = x;
if (y < 0) {
base = 1.0 / base;
}
while (y != 0.0) {
if (y % 2) {
z *= base;
}
y /= 2;
base *= base;
}
return z;
}