Integer number of values

Source: Internet
Author: User

Solution One: a bad solution

Double Power (double base,int exponent)

{

Double result=1.0;

for (int i=1;i<=exponent;++i)

Result*=base;

return result;

}

Solution one does not consider the case of exponential 0 and negative numbers, only the case that the exponent is positive is considered.

Solution Two: A comprehensive but not efficient solution

BOOL Q_invalidinput = false;
Double Power (double base, int exponent)
{
G_invalidinput = false;
if (equal (base, 0.0) && exponent < 0)
{
G_invalidinput = true;
return 0.0;
}
unsigned int absexponent = (unsigned int) (exponent);
if (Exponent < 0)
Absexponent = (unsigned int) (-exponent);
Double result = Powerwithunsignedexponent (base,absexponent);
if (Exponent < 0)
result = 1.0/result;
return result;
}
Double powerwithunsignedexponent (double base, unsigned int exponent)
{
Double result = 1.0;
for (int i = 1; I <= exponent; ++i)
Result *= base;
return result;
}
bool Equal (double NUM1, double num2)
{
if ((Num1-num2 > -0.0000001) && (num1-num2) < 0.0000001))
return true;
Else
return false;
}

Solution Three: A comprehensive and efficient solution
Use a formula to find the n-th side of a:
The double powerwithunsignedexponent function of the solution two is modified to:

Double powerwithunsignedexponent (double base, unsigned int exponent)
{
if (exponent = = 0)
return 1;
if (exponent = = 1)
return base;
Double result = powerwithunsignedexponent (base, exponent >> 1);
Result *= result;
if (exponent & 0x1 = = 1)
Result *= base;
return result;
}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Integer number of values

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.