Isn't this one way to test whether a number is a power of 2?
boolean isPowerOfTwo(int n) {
return (n%2==0);
}
Are you sure that you are checking power of 2? Rather, being checked divisible with 2. If you are serious, use the piece of cake snippet
return n > 0 && ((n & -n) == n);
The second way,
private static boolean powerOf2(int num)
{
if(num <= 0){
return false;
}
while(num > 1)
{
if(num % 2 != 0)
{
return false;
}
num = num / 2;
}
return true;
}
That function checks whether or not an integer is even (i.e divisible by 2), not whether or not the integer is a power of 2.
To check if a number is a power of 2, you should look at its bits. ints that are a power of 2 will have one bit set to 1 and all others set to 0.
boolean isPowerOf2(int i) {
return Integer.bitCount(i) == 1;
}
The % is the modulo operator, meaning the remainder after division. your method checks if the int n is divisible by 2
Related
I'm trying to implement a method which checks any integer and returns true if it's prime using Fermat's primality test.
I divided the problem depending on whether the input is less than 40 or not. If the input is less than 40 then I apply the test for every integer up until n-1. Else, if the integer is greater than 40 then the test is applied for every integer up until 40. However, it fails for some primes.
public static boolean isPrime (double n){
int counter=0;
boolean isPrime=false;
if(n<40) {
for (int a = 2; a < n - 1; a++) {
if (Math.pow(a, n - 1) % n == 1) counter++;
}
if (counter == n - 3) isPrime = true;
}
else {
for (int a = 2; a <= 40; a++) {
if (Math.pow(a, n - 1) % n == 1) counter++;
}
if (counter == 39) isPrime = true;
}
return isPrime;
}
Is it a logical issue or something else?
Math.pow works on doubles and the result is only approximate. Modulo on the other hand works on ints which have a range up to a little over 2 billion, is your pow producing some numbers larger than that by any chance? (17^18 seems to be a sure bet for 19...)
So how to fix this:
you can implement your own pow(a,b,n) (power modulo n) using multiplication and modulo on integers. That should work correctly. Make a function to raise a to power b using a series of multiplications, apply %n to the intermediate result after each step...
I write down a code which find out quotient after dividing two number but without using multiplication,division or mod operator.
My code
public int divide(int dividend, int divisor) {
int diff=0,count=0;
int fun_dividend=dividend;
int fun_divisor=divisor;
int abs_dividend=abs(dividend);
int abs_divisor=abs(divisor);
while(abs_dividend>=abs_divisor){
diff=abs_dividend-abs_divisor;
abs_dividend=diff;
count++;
}
if(fun_dividend<0 && fun_divisor<0){
return count;
}
else if(fun_divisor<0||fun_dividend<0) {
return (-count);
}
return count;
}
My code passes the test cases like dividend=-1, divisor=1 or dividend=1 and divisor=-1. But it cannot pass the test case like dividend = --2147483648 and divisor =-1. However I have a if statement when both inputs are negative.
if(fun_dividend<0 && fun_divisor<0){
return count;
}
When my inputs are -2147483648 and -1 it returned zero. I debugged my code and find out that it cannot reach the the inner statements of while loop. It just check the while loop and terminated and execute
if(fun_dividend<0 && fun_divisor<0){
return count;
}
It is very obvious, both inputs are negative, so I was using Math.abs function to make them positive. But when I try to see the values of variables abs_dividend and abs_divisor they show me negative values.
Integer max can take a 9 digit number. So how could I pass this test case? As per this test case dividend is a 10 digit number which is not valid for a integer range.
As per the test case the output that I get should be 2147483647.
How could I solve the bug?
Thank you in advance.
Try using the bit manipulation for this as follows:
public static int divideUsingBits(int dividend, int divisor) {
// handle special cases
if (divisor == 0)
return Integer.MAX_VALUE;
if (divisor == -1 && dividend == Integer.MIN_VALUE)
return Integer.MAX_VALUE;
// get positive values
long pDividend = Math.abs((long) dividend);
long pDivisor = Math.abs((long) divisor);
int result = 0;
while (pDividend >= pDivisor) {
// calculate number of left shifts
int numShift = 0;
while (pDividend >= (pDivisor << numShift)) {
numShift++;
}
// dividend minus the largest shifted divisor
result += 1 << (numShift - 1);
pDividend -= (pDivisor << (numShift - 1));
}
if ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)) {
return result;
} else {
return -result;
}
}
I solve it this way. Give preference to data type long over int wherever there is a chance of overflow upon left-shift. Handle the edge case at the very beginning to avoid the input values getting modified in the process. This algorithm is based upon the division technique we used to make use in school.
public int divide(int AA, int BB) {
// Edge case first.
if (BB == -1 && AA == Integer.MIN_VALUE){
return Integer.MAX_VALUE; // Very Special case, since 2^31 is not inside range while -2^31 is within range.
}
long B = BB;
long A = AA;
int sign = -1;
if ((A<0 && B<0) || (A>0 && B>0)){
sign = 1;
}
if (A < 0) A = A * -1;
if (B < 0) B = B * -1;
int ans = 0;
long currPos = 1; // necessary to be long. Long is better for left shifting.
while (A >= B){
B <<= 1; currPos <<= 1;
}
B >>= 1; currPos >>= 1;
while (currPos != 0){
if (A >= B){
A -= B;
ans |= currPos;
}
B >>= 1; currPos >>= 1;
}
return ans*sign;
}
Ran with the debugger and found that abs_dividend was -2147483648.
Then the comparison in while (abs_dividend >= abs_divisor) { is false and count is never incremented.
Turns out the explanation is in the Javadoc for Math.abs(int a):
Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.
Presumably, this is because Integer.MAX_VALUE is 2147483647, so there is no way of representing positive 2147483648 with an int. (note: 2147483648 would be Integer.MAX_VALUE + 1 == Integer.MIN_VALUE)
I recently has a test in university and I was struggling with a problem. The task was defined very specifically as following:
Write a recursive method (don't change the signature, or parameters; no global variables allowed; don't use Strings or the method Stringbuffer; no loops) which returns "true" if the number of zeros in number "n" is odd and "false" if the number of zeros is even.
Signature and Parameter:
public static boolean oddZeros(int n) {
}
So for:
n = 10 //true
n = 100 //false
n = 1402050 //true
n = 0 // true
n = 12 // false
you get the idea..
I understand the concept of recursion but i fail to see how i can count something, given only booleans. I tried adding a counter variable inside the method but whenever i make a recursive call, obviously the variable would be reset to its initialization.
Since this is a very specific problem, i didn't find any solutions so far. How would a method like this look like?
public static boolean oddZeroes(int n) {
if (n < 10) {
return n == 0;
}
return (n % 10 == 0) ^ oddZeroes(n / 10);
}
You can even make it one-liner:
public static boolean oddZeroes(int n) {
return n < 10 ? n == 0 : (n % 10 == 0) ^ oddZeroes(n / 10);
}
And if you want to process negative inputs as well, add something like if (n < 0) {return oddZeroes(-n);} in the beginning, i.e.:
public static boolean oddZeroes(int n) {
if (n < 0) {
return oddZeroes(-n);
}
if (n < 10) {
return n == 0;
}
return (n % 10 == 0) ^ oddZeroes(n / 10);
}
You don't have to count anything.
You only have to observe that:
if you remove a 0 digit from a number that has an odd number of zeroes, the resulting (smaller) number does not have an odd number of zeroes.
if you remove a non 0 digit from a number that has an odd number of zeroes, the resulting (smaller) number also has an odd number of zeroes.
Finally, as the base of the recursion, if 0 < number < 10, it has an even number of 0s (0 0s), so your method should return false.
You can write a shorter implementation, but I preferred readability:
public static boolean oddZeros(int n) {
if (n == 0)
return true;
else if (n < 10)
return false;
else if (oddZeros (n / 10)) {
return n % 10 != 0; // removed digit is not 0
} else {
return n % 10 == 0; // removed digit is 0
}
}
EDIT:
This assumes the input is non-negative. If you need to support negative input, you can add an initial condition of:
if (n < 0) {
return oddZeros (-n);
}
Hi I'm having a little problem about prime function.
public static boolean isPrime(long num) {
for (long i=3; i <num/2; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
I don't understand why it has to be num/2 and the if(num % i == 0).
so does it mean that if
num = 10 and i = 4 which would result to 2. makes 4 a prime number?
sorry if it's a stupid question, I just started coding \m/
edit: also, can someone explain the if(num % 1 ==0)
if you want to write a code to check whether is it is prime number or not then you need to change loop initialization.
long i=3 --> long i=2. Because prime number should not be divisible by any number other than 1. So you should start divide the number by 2,
Problem: check if a number is a power of 4.
my solution in java:
public static boolean isPowerOfFour(int num) {
return (Math.log(num) % Math.log(4) == 0);
}
But it seems off in some cases, for example when num is 64.
I found out that if I change the code a little bit, it works well.
public static boolean isPowerOfFour(int num) {
return (Math.log(num) / Math.log(4) %1 == 0);
}
I think both solutions do the same thing, check if the remaining of logNum/logBase is 0. But why the first solution doesn't work? Is it because the solution is incorrect or relative to some low level JVM stuff?
Thanks.
Building on #dasblinkenlight's answer, you can easily combine both conditions (first, a power of 2, then any power of 4 among all possible powers of 2) with a simple mask:
public static boolean isPowerOfFour(int num) {
return ((( num & ( num - 1 )) == 0 ) // check whether num is a power of 2
&& (( num & 0xaaaaaaaa ) == 0 )); // make sure it's an even power of 2
}
No loop, no conversion to float.
Checking if a number is a power of 4 is the same as checking that the number is an even power of 2.
You can check that a number x is a power of two by verifying that x & (x-1) is zero (here is the explanation of how this works)
If your number is not a power of 2, return false. Otherwise, shift the number right until you get to one, and count the number of shifts. If you shifted an odd number of times, return false; otherwise, return true:
public static boolean isPowerOfFour(int num) {
if ((num & (num-1)) != 0) {
return false;
}
int count = 0;
while (num != 1) {
num >>= 1;
count++;
}
return count % 2 == 0;
}
Demo.
Functions like Math.log return floating point numbers with a rounding error. So when num = 64 for example, Math.log (num) / Math.log (4) is not exactly 3, but a number close to 3.
public static boolean isPowerOfFour(int num) {
if (num > 0) {
while (num % 4 == 0) num /= 4;
}
return (num == 1);
}
This solution can be quite easily adapted to check whether num is a power of some other integer greater than 1.
The reason it doesn't work is because Math.log() returns a double. The answer of false is reflective of rounding errors; log(64) base e is an irrational number but Java needs to truncate it to fit it's width.