Write
a function named factorTwoCount that returns the number of times that 2
divides the argument.
For
example, factorTwoCount(48) returns 4 because
48/2
= 24
24/2
= 12
12/2
= 6
6/2
= 3
2
does not divide 3 evenly.
Another
example: factorTwoCount(27) returns 0 because 2 does not divide 27.
The
function signature is
int factorTwoCount(int n);
public static int factorTwoCount(int n) { int count = 0; while (n > 1) { if (n % 2 == 0) { n = n / 2; count++; } else { break; } } return count; }Second way :
public static int factorTwoCount(int n) { int count = 0; bool flag = false; double temp = n; do { temp = temp / 2; flag = (temp % 1 == 0); if (flag) { count++; } } while (flag); return count; }
Nice blog
ReplyDeleteNice job my friend
ReplyDeleteThank you #jayanta
Deletethe first code is not correct, it will not work for negative numbers.
ReplyDeleteand second one will run forever if n = 0;
# this is a better code
ReplyDeletepublic static int factorTwo(int n){
int count = 0;
while(n % 2 ==0){
count += 1;
n /=2;
}
return count;
}
This comment has been removed by the author.
Delete