HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Find the largest exponent x such that p^x evenly divides n

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
suchtheexponentdivideslargestthatfindevenly

Problem

Write a method getExponent(n, p) that returns the largest exponent
x 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 of x here is 4.



  • if n is 27 and p is 3, return 3 because 33 divides 27 evenly but 34 does not.



  • if n is 28 and p is 3, return 0 because 30 divides 28 evenly but 31 does not.



  • if n is 280 and p is 7, return 1 because 71 divides 280 evenly but 72 does not.



  • if n is -250 and p is 5, return 3 because 53 divides -250 evenly but 54 does not.



  • if n is 18 and p is 1, return -1 because if p



  • if n is 128 and p is 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":

if (p <= 1) {
    return -1;
}


The status variable is not needed, the while-loop can be
simplified 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.