日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

求幂运算、多项式乘法及Horner法则的应用

發(fā)布時間:2025/6/17 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 求幂运算、多项式乘法及Horner法则的应用 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

一,兩種不同的求冪運算

求解x^n(x 的 n 次方)

①使用遞歸,代碼如下:

1 private static long pow(int x, int n){ 2 if(n == 0) 3 return 1; 4 if(n == 1) 5 return x; 6 if(n % 2 == 0) 7 return pow(x * x, n / 2); 8 else 9 return pow(x * x, n / 2) * x; 10 }

分析:

每次遞歸,使得問題的規(guī)模減半。2到6行操作的復雜度為O(1),第7行pow函數(shù)里面的x*x操作復雜度為O(1)

故時間復雜度公式:T(N)=T(N/2)+O(1)?? =>?? T(N)=O(logN)

?

②普通方式求冪

1 private static long pow2(int x, int n){ 2 if(x == 0) 3 return 0;//0^n == 0 4 long p = 1; 5 for(int i = 0; i < n; i++) 6 p *= x; 7 return p; 8 }

顯然,時間復雜度為O(N)

?

二,求解多項式乘法

公式:f(x,n) = a(0)x^0 + a(1)x^1 + a(2)x^2+...+a(n)x^n

比如:f(10,4)=a(0)10^0 + a(1)10^1 + a(2)10^2 + a(3)10^3+a(4)10^4

代碼如下:

1 public static long poly(int[] arr, int x, int n){ 2 long sum = 0; 3 for(int i = 0; i <= n; i++){ 4 sum += arr[i] * pow(x, i); 5 } 6 return sum; 7 } 8 9 private static long pow(int x, int n){ 10 if(n == 0) 11 return 1; 12 if(n == 1) 13 return x; 14 if(n % 2 == 0) 15 return pow(x * x, n / 2); 16 else 17 return pow(x * x, n / 2) * x; 18 }

?

Horner法則求解多項式乘法,參考:

1 public static long poly2(int[] arr, int x, int n){//arr存儲系數(shù), x 表示基數(shù), n 表示冪 2 long poly = 0; 3 for(int i = n; i >= 0; i--) 4 poly = poly * x + arr[i]; 5 return poly; 6 }

對比采用Horner法則計算多項式乘法與這篇文章: 字符串轉(zhuǎn)換成數(shù)字

1 public int atoi(char[] s){ 2 int result = 0; 3 for(int i = 0; i < s.length; i++) 4 result = result * 10 + s[i] - '0';// 相當于 poly2(...)中的 x=10 5 return result; 6 }

可以看出,二者有很大的相似性。其實,不難看出,字符串轉(zhuǎn)換成數(shù)字使用的正是Horner法則。

?

由此,得到啟發(fā),在進制轉(zhuǎn)換中,如:八進制轉(zhuǎn)十進制,相當于 x = 8。

故可寫出一個常用的進制轉(zhuǎn)換程序,如下:

//x 表示進制, 若x=8,表示將8進制轉(zhuǎn)換成10進制public static long convert(char[] arr, int x){long result = 0;for(int i = 0; i < arr.length; i++)result = result * x + arr[i] - '0';return result;}//str 表示原來進制的數(shù),如:convert("456", 8) 456 --> 302public static long convert2(String str, int x){long result = 0;for(int i = 0; i < str.length(); i++)result = result * x + Integer.valueOf(str.charAt(i) - '0');return result;}

?

十六進制轉(zhuǎn)十進制,相當于 x = 16。

public static long convert2(String str, int x){//x = 16long result = 0;char c;str = str.toUpperCase();//"abF8"-->"ABF8"for(int i = 0; i < str.length(); i++){c = str.charAt(i);if(c >= 'A' && c <= 'F')result = result * x + (c - 'A') + 10;elseresult = result * x + c - '0';}return result;}

?

因此,進制轉(zhuǎn)換、字符串轉(zhuǎn)換成數(shù)字、多項式求值都可以使用Horner法則來求解。

?

轉(zhuǎn)載于:https://www.cnblogs.com/hapjin/p/5372930.html

總結(jié)

以上是生活随笔為你收集整理的求幂运算、多项式乘法及Horner法则的应用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。