i am reading section about A Binary Recursive Gcd Algorithm,where this definition is given let v_2(a) denotes the 2-adic valuation of a, i.e. the number of consecutive zeroes in the least signicant bits of the binary representation of a ,so i am trying to find v_2(a) here is code for this
#include <iostream>
using namespace std;
int main()
{
int total=0;
int n,k;
cout << "enter value n ";
k=0;
cin >> n;
while(k!=1)
{
if (k==1)
{
break;
}
k=n%2;
n>>=1;
total++;开发者_JS百科
}
cout<<total<<" "<<endl;
return 0;
}
when i enter number 12 (in binary it is 1100) it should give me number 2 but it shows 3,what is wrong?please help me
You're breaking out of the while too late, since you're running total++
when k==1
has been reached.
Move the if (k==1)
block after the k=n%2;
line.
Note: The k
variable isn't actually necessary. You could simplify the loop to:
while((n%2)==0) {
n>>=1;
total++;
}
精彩评论