Seeking a number of continuous power and

Problem: Find X n- + X n-. 1- X n--2 + ... + X 0 value.

The first is relatively straightforward naive algorithm.

@get_time
 DEF sum_power (X, n-):
     "" " 
    . Direct simple algorithm, for example, x = 5, n = 5 when made a total of 5 times addition, 1 + 2 + 3 + 4 = 10 multiplications. 
    : param X: 
    : n-param: 
    : return: 
    "" " 
    RES = 0
     the while n-> = 0: 
        RES + X ** = n- 
        n- - =. 1
     return RES
Simple algorithm

The second is Horner's method.

@get_time
 DEF sum_power1 (X, n-):
     "" " 
    Horner's method to calculate the value x ** 2, then x * (x ** 2), then x * (x * (x ** 2)). such a result can be used every time last calculated. 
    made a total of four multiplications, additions 5 simple direct comparison algorithm, multiplication of one order of magnitude less.. 
    : param X: 
    : n-param: 
    : return: 
    " "" 
    RES = 0 
    m =. 1
     the while n-> = 0: 
        RES + = m 
        m = X * m 
        n- - =. 1
     return RES

 

Guess you like

Origin www.cnblogs.com/walle-zhao/p/11695920.html