ในปัญหานี้ เราได้รับจำนวนเต็ม x และ n สองจำนวน งานของเราคือการเขียนโปรแกรมเพื่อคำนวณ pow(x,n)
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
อินพุต
x = 5 , n = 3
ผลลัพธ์
125
โปรแกรมคำนวณ pow(x,n),
ตัวอย่าง
#include <iostream>
using namespace std;
float myPow(float x, int y) {
if(y == 0)
return 1;
float temp = myPow(x, y / 2);
if (y % 2 == 0)
return temp*temp;
else {
if(y > 0)
return x*temp*temp;
else
return (temp*temp)/x;
}
}
int main() {
float x = 5;
int n = 7;
cout<<x<<" raised to the power "<<n<<" is "<<myPow(x, n);
return 0;
} ผลลัพธ์
5 raised to the power 7 is 78125
โปรแกรมแสดงแนวทางที่มีประสิทธิภาพโดยแบ่งกำลังเป็นครึ่งหนึ่งแล้วคูณทั้งสองครึ่งและพิจารณากรณีเชิงลบด้วย