私は、正の整数Nをx^yとして表すことができるかどうかを決定するこのアルゴリズムの時間複雑度を計算しようとしています。アルゴリズムの作成者はVaibhav Guptaです。このアルゴリズムの時間計算量を計算する
// Returns true if n can be written as x^y
bool isPower(unsigned int n)
{
// Base case
if (n <= 1) return true;
// Try all numbers from 2 to sqrt(n) as base
for (int x=2; x<=sqrt(n); x++)
{
unsigned p = x;
// Keep multiplying p with x while is smaller
// than or equal to x
while (p <= n)
{
p *= x;
if (p == n)
return true;
}
}
return false;
}
著者は、このアルゴリズムは最初の1の最適化バージョンであることを言う:
// Returns true if n can be written as x^y
bool isPower(unsigned n)
{
if (n==1) return true;
// Try all numbers from 2 to sqrt(n) as base
for (int x=2; x<=sqrt(n); x++)
{
unsigned y = 2;
unsigned p = pow(x, y);
// Keep increasing y while power 'p' is smaller
// than n.
while (p<=n && p>0)
{
if (p==n)
return true;
y++;
p = pow(x, y);
}
}
return false;
}
んこの最初の一つは、彼が捕虜機能を使用していますので、異なる時間の複雑さを持っていますか?外側のループは、nの平方根であるよう
私にとっては、 'if(n%x!= 0)continue;' 'while'の直前にチェックがないことは非常に奇妙です。この最適化を避ける理由はありますか? – Ilya
@ilya - 質問はそれに関するものではありません。アルゴリズム*の複雑さについて書かれています*。 –