Self-implemented POW (double base, unsigned exponent)

Source: Internet
Author: User

The question comes from offoffoffoffer. Description:

Implement the function Double POW (double base, unsigned exponent)

Here are a few notes:

1. exponent may be positive or negative.

2. When base is 0 and exponent is negative, the result is not defined in mathematics.

3. Use of mathematical formulas:

A ^ (n/2) * A ^ (n/2) N is an even number.

A ^ n = a ^ (n-1)/2) * A ^ (n-1)/2) * a n is an odd number

The Code is as follows:

# Include <iostream> # include <cstdio> using namespace STD; bool valid_input = false; // determine whether the input is valid bool equal (double num1, double num2) based on this value) // determine whether two values are equal {If (num1-num2>-1e-6 & num1-num2 <1e-6) return true; return false ;} /// // a ^ (n/2) * A ^ (n/2) N is an even number // a ^ n = // a ^ (n/2) * A ^ (n/2) * a n is an odd number // double pow_with_unsigned (double base, unsigned int exponent) {If (exponent = 0) // The 0 power of any number is 1 return 1; if (exponent = 1) return base; double result = pow_with_unsigned (base, exponent> 1); Result * = result; If (exponent & 0x01 = 1) // returns an odd number of results * = base; return result;} double POW (double base, int exponent) {valid_input = false; If (equal (base, 0.0) & exponent <0) // when the base number is 0, when its power is a negative number, the specified input is invalid, and it returns 0 (1 can also be used, indicating that the input is incorrect) {valid_input = true; return 0.0; // The base number is 0, returns 0.0 if the index is less than 0, and indicates that the input is invalid} unsigned int abs_exponent = (unsigned INT) exponent; If (exponent <0) abs_exponent = (unsigned INT) (-exponent ); double result = pow_with_unsigned (base, abs_exponent); If (exponent <0) // If the index is smaller than 0, the reciprocal result of the result is 1.0/result; return result ;} int main (void) {double rel = POW (0,-3); cout <rel <Endl; return 0 ;}

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.