美国程序员面试题
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
0 because there are too many 1s
0 because there are too many 1s
0 because not all values are positive
0 because 0 occurs one time, not zero times.
because the 2s are not in consec
utive locations
isOddHeavy should return
1
int getExponent(int n, int p)
样例:
java 实现代码:
package com.zzy;
/**
* 更多请关注: http://huamaodashu.com
* Created by huamaodashu on 23/07/2018.
*/
public class Exponent {
public static void main(String[] args) {
// System.out.println(28%4);
System.out.println(getExponent(128,4));
}
public static int getExponent(int n,int p){
System.out.println(Math.sqrt(n));
int x=0;
if(n<0){
n = Math.abs(n);
}
if(p<=1){
return -1;
} else {
for (int i = (int) Math.sqrt(n); i > 0; i--) {
int tmp = (int) Math.pow(p, i);
if (tmp <= n ) {
if (n % tmp == 0) {
x=i;
break;
// return i;
}
}
}
}
return x;
}
}