patternjavaMinor
Find the largest exponent x such that p^x evenly divides n
Viewed 0 times
suchtheexponentdivideslargestthatfindevenly
Problem
Write a method
x such that px evenly divides n. If p ≤ 1 the method should return -1.
I wrote following code to test that result
I checked whether
getExponent(n, p) that returns the largest exponentx such that px evenly divides n. If p ≤ 1 the method should return -1.
getExponent(162, 3)returns 4 because 162 = 21∙ 34, therefore the value ofxhere is 4.
- if
nis 27 andpis 3, return 3 because 33 divides 27 evenly but 34 does not.
- if
nis 28 andpis 3, return 0 because 30 divides 28 evenly but 31 does not.
- if
nis 280 andpis 7, return 1 because 71 divides 280 evenly but 72 does not.
- if
nis -250 andpis 5, return 3 because 53 divides -250 evenly but 54 does not.
- if n
is 18 andpis 1, return -1 because ifp
- if
nis 128 andpis 4, return 3 because 43 divides 128 evenly but 44 does not.
I wrote following code to test that result
public class Exponent {
public static void main(String args[]) {
int n = 27;
int p = 3;
System.out.println("result is: " + getExponent(n, p));
}
public static int getExponent(int n, int p) {
int count = 0;
if (p <= 1) {
count = -1;
} else {
boolean status = true;
while (status) {
if (n % p == 0) {
count++;
n = n / p;
} else {
status = false;
break;
}
}
}
return count;
}
}I checked whether
n is divisible by p or not. If divisible, then increment count and return count. Is this the right way to do that?Solution
I would do an "early exit" in the case \$ p \le 1 \$ and
save an indentation level for the "main case":
The
simplified to
Your program should check if the input number \$ n \$
is zero, otherwise it will run into an infinite loop in that case.
save an indentation level for the "main case":
if (p <= 1) {
return -1;
}The
status variable is not needed, the while-loop can besimplified to
int count = 0;
while (n % p == 0) {
count++;
n = n / p;
}Your program should check if the input number \$ n \$
is zero, otherwise it will run into an infinite loop in that case.
Code Snippets
if (p <= 1) {
return -1;
}int count = 0;
while (n % p == 0) {
count++;
n = n / p;
}Context
StackExchange Code Review Q#117220, answer score: 6
Revisions (0)
No revisions yet.