Question :
Write a method named getExponent(n,
p) that returns the largest exponent x such that px evenly
divides n. If p is <= 1 the method should return -1.
For example, getExponent(162,
3) returns 4 because 162 = 21 * 34, therefore the value
of x here is 4.
The method signature is
int getExponent(int n, int p)
Examples:
if n is
|
and p is
|
return
|
Because
|
27
|
3
|
3
|
33 divides 27 evenly but 34 does not.
|
28
|
3
|
0
|
30 divides 28 evenly but 31 does not.
|
280
|
7
|
1
|
71 divides 280 evenly but 72 does
not.
|
-250
|
5
|
3
|
53 divides -250 evenly but 54 does
not.
|
18
|
1
|
-1
|
if p <=1 the function returns -1.
|
128
|
4
|
3
|
43 divides 128 evenly but 44 does not.
|
public static int getExponent(int n, int p)
{
if (p <= 1) return -1;
bool isok = false;
int x = 0;
double temp = n;
do
{
temp = temp / p;
isok = (temp % 1 == 0);
if (isok)
{
x++;
}
} while (isok);
return x;
}
this loop runs forever if n = 0
ReplyDeleteyou should include if(n == 0) return -1;
ReplyDelete0 can't be represented by the above code