Учитывая два положительных числа x и y, проверьте, является ли y степенью x или нет.
Примеры :
Ввод: x = 10, y = 1
Выход: True
х ^ 0 = 1
Ввод: x = 10, y = 1000.
Выход: True
х ^ 3 = 1
Ввод: x = 10, y = 1001.
Выход: ложь
Рекомендуется: сначала решите эту проблему на «ПРАКТИКЕ», прежде чем переходить к решению.
A simple solution is to repeatedly compute powers of x. If a power becomes equal to y, then y is a power, else not.
C++
#include <bits/stdc++.h>
using namespace std;
bool isPower( int x, long int y)
{
if (x == 1)
return (y == 1);
long int pow = 1;
while ( pow < y)
pow *= x;
return ( pow == y);
}
int main()
{
cout << isPower(10, 1) << endl;
cout << isPower(1, 20) << endl;
cout << isPower(2, 128) << endl;
cout << isPower(2, 30) << endl;
return 0;
}
|
Java
public class Test {
public static void main(String[] args)
{
System.out.println(isPower( 10 , 1 ) ? 1 : 0 );
System.out.println(isPower( 1 , 20 ) ? 1 : 0 );
System.out.println(isPower( 2 , 128 ) ? 1 : 0 );
System.out.println(isPower( 2 , 30 ) ? 1 : 0 );
}
public static boolean isPower( int x, int y)
{
if (x == 1 )
return (y == 1 );
int pow = 1 ;
while (pow < y)
pow = pow * x;
return (pow == y);
}
}
|
Python3
def isPower (x, y):
if (x = = 1 ):
return (y = = 1 )
pow = 1
while ( pow < y):
pow = pow * x
return ( pow = = y)
if (isPower( 10 , 1 )):
print ( 1 )
else :
print ( 0 )
if (isPower( 1 , 20 )):
print ( 1 )
else :
print ( 0 )
if (isPower( 2 , 128 )):
print ( 1 )
else :
print ( 0 )
if (isPower( 2 , 30 )):
print ( 1 )
else :
print ( 0 )
|
C#
using System;
class GFG
{
public static bool isPower ( int x, int y)
{
if (x == 1)
return (y == 1);
int pow = 1;
while (pow < y)
pow = pow * x;
return (pow == y);
}
public static void Main ()
{
Console.WriteLine(isPower(10, 1) ? 1 : 0);
Console.WriteLine(isPower(1, 20) ? 1 : 0);
Console.WriteLine(isPower(2, 128) ? 1 : 0);
Console.WriteLine(isPower(2, 30) ? 1 : 0);
}
}
|
PHP
<?php
function isPower( $x , $y )
{
if ( $x == 1)
return ( $y == 1 ? 1 : 0);
$pow = 1;
while ( $pow < $y )
$pow *= $x ;
return ( $pow == $y ? 1 : 0);
}
echo isPower(10, 1) . "
" ;
echo isPower(1, 20) . "
" ;
echo isPower(2, 128) . "
" ;
echo isPower(2, 30) . "
" ;
?>
|
Javascript
<script>
function isPower(x, y)
{
if (x == 1)
return (y == 1);
let pow = 1;
while (pow < y)
pow = pow * x;
return (pow == y);
}
document.write((isPower(10, 1) ? 1 : 0) + "<br/>" );
document.write((isPower(1, 20) ? 1 : 0) + "<br/>" );
document.write((isPower(2, 128) ? 1 : 0) + "<br/>" );
document.write((isPower(2, 30) ? 1 : 0) + "<br/>" );
</script>
|
Выход:
1
0
1
0
Временная сложность вышеуказанного решения составляет O (Log x y)
Оптимизация:
Мы можем оптимизировать вышеуказанное решение для работы в O (Log Log y). Идея состоит в том, чтобы возвести мощность в квадрат вместо умножения ее на x, то есть сравнить y с x ^ 2, x ^ 4, x ^ 8 и т. Д. Если x становится равным y, верните true. Если x становится больше, чем y, мы выполняем двоичный поиск мощности x между предыдущей мощностью и текущей мощностью, то есть между x ^ i и x ^ (i / 2).
Ниже приведен подробный шаг.
1) Initialize pow = x, i = 1
2) while (pow < y)
{
pow = pow*pow
i *= 2
}
3) If pow == y
return true;
4) Else construct an array of powers
from x^i to x^(i/2)
5) Binary Search for y in array constructed
in step 4. If not found, return false.
Else return true.
Alternate Solution :
The idea is to take log of y in base x. If it turns out to be an integer, we return true. Else false.
C++
#include <iostream>
#include <math.h>
using namespace std;
bool isPower( int x, int y)
{
int res1 = log (y) / log (x);
double res2 = log (y) / log (x);
return (res1 == res2);
}
int main()
{
cout << isPower(27, 729) << endl;
return 0;
}
|
Java
class GFG
{
static boolean isPower( int x,
int y)
{
int res1 = ( int )Math.log(y) /
( int )Math.log(x);
double res2 = Math.log(y) /
Math.log(x);
return (res1 == res2);
}
public static void main(String args[])
{
if (isPower( 27 , 729 ))
System.out.println( "1" );
else
System.out.println( "0" );
}
}
|
Python3
import math
def isPower(x, y):
res1 = math.log(y) / / math.log(x);
res2 = math.log(y) / math.log(x);
return 1 if (res1 = = res2) else 0 ;
if __name__ = = "__main__" :
print (isPower( 27 , 729 ));
|
C#
using System;
class GFG
{
static bool isPower( int x, int y)
{
int res1 = ( int )Math.Log(y) /
( int )Math.Log(x);
double res2 = Math.Log(y) /
Math.Log(x);
return (res1 == res2);
}
static void Main()
{
if (isPower(27, 729))
Console.WriteLine( "1" );
else
Console.WriteLine( "0" );
}
}
|
PHP
<?php
function isPower( $x , $y )
{
$res1 = log( $y ) / log( $x );
$res2 = log( $y ) / log( $x );
return ( $res1 == $res2 );
}
echo isPower(27, 729) ;
?>
|
Javascript
<script>
function isPower(x, y)
{
var res1 = parseInt(Math.log(y)) /
parseInt(Math.log(x));
var res2 = Math.log(y) /
Math.log(x);
return (res1 == res2);
}
if (isPower(27, 729))
document.write( "1" );
else
document.write( "0" );
</script>
|
Выход :
1
Спасибо Gyayak Jain за предложение этого решения.
Автор статьи - Маниш Гупта . Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше
Вниманию читателя! Не прекращайте учиться сейчас. Получите все важные математические концепции для соревновательного программирования с курсом Essential Maths for CP по доступной для студентов цене. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .