Why by using n&(n-1) is not able to calculate number of 1's bits? - bit-manipulation

I found a video on youtube that says by using n&(n-1) we can able to count number of 1's bits and it's much faster than - right shifting the bits by one and then checking the last bit . When I wrote the code using this method to calculate number of bits it's giving output as 9 instead of 3 - if we 01011 as parameter.
I debug the program and not able to find why it's happening so ?I am confused when in while loop condition , both A and A-1 is 512, it get out of loop even A&(A-1) = 1000000000 not 0 (zero).
If anyone knows what I am missing please let me know .
#include <iostream>
using namespace std;
int bits(unsigned int A){
int counter=0;
unsigned int t;
while (A&(A-1))
{
counter++;
A--;
}
return counter;
}
int main()
{
unsigned int A=01011;
int res=bits(A);
cout<<"Result is "<<res<<"\n";
return 0;
}
Thanking You
Yours Truly,
Rishabh Raghwendra

This is the Kerningham trick to calculate the number of bits without shifting. (Original author precedes Kerningham by a decade, but mr K popularised it).
n&(n-1) peels off the least significant one, meaning that one should write the result back to n.
while (n) {
++counter;
n&=n-1;
}

Related

Division between a large numbers (Above long long) and a single integer

I am trying to divide a number by an integer as suggested in the title, and i am having a hard time doing so. I was thinking about inserting the big number's digits into a vector then repeatedly substracting said digit from the vector until it is null. However, i cannot find the code to do it. Here is what i have been trying so far:
#include <fstream>
using namespace std;
int v[100],r[100]; //In v i store the initial number,in r i store the result
int main()
{
FILE*fin=fopen("imp.in","r");
FILE*fout=fopen("imp.out","w");
int n,x,c,w,k,m=2;
fscanf(fin,"%d",&n); //Reads the number of digits the number has
for(;n>0;--n)
{
fscanf(fin,"%d",&x);
v[n]=x;
}
fscanf(fin,"%d",&c); //Reads the digit it has to be divided by
while(v[n]!=0)
{
k=0;
while(v[1]>=c)
{
v[1]-=c;
++k;
}//As long as the first position in vector can be substracted, increase k
--v[2];
v[1]+=10;
/* Because first position will be negative, take one from second position and add ten in the first*/
w=2;
while(v[w]<0)
{
v[w]=9;
--v[w+1];
++w;
}
/*When, for example, you substract one from 1000,it will become 999. This loop helps do that*/
r[1]+=k;
if(r[1]>9)
{
r[1]-=10;
w=2;
++r[2];
while(r[w]>9)
{
++r[w+1];
r[w]=0;
++w;
if(w>m)m=w;
}
}
/*If statement and the line of code above it inserts the result into r[100]*/
}
for(;w>0;--w)fprintf(fout,"%d",r[w]);
return 0;
}
You can use GMP rather than write it yourself from scratch. It will take you less time to download the GMP sources, build it, and learn how to use it, than to write it yourself.
Pencil and paper division in base 2^32, or 2^64, would be a lot more efficient than "division by subtraction" and I believe that GMP employs a better algorithm than that.
With GMP you'd write:
mpz_class a("134897563047067890568704560457984059182035823590780968094759123590346040967804956029586405960249562895760983475187459073406984560900123895702851034560016405716045613495619456196450196450165901268051620465016405634056104951923845902387581");
std::cout << a / 7 << std::endl;

trailing zeros in a factorial.when i run it on ideone.com i'm getting runtime error with infinite output. Even SPOJ is also not accepting

#include <iostream>
#include <cmath>
using namespace std;
int func(int n){
int count=0;
float t=log(n)*0.621;
int k=(int)t;
int temp;
for(int i=1;i<=k;i++){
int power=1;
for(int j=0;j<i;j++){
power=power*5;
}
temp=(int)(n/power);
count=count+temp;
}
return count;
}
int main(){
int t;
cin>>t;
for (int i=0;i<t;i++){
int n;
cin>>n;
cout<<func(n)<<'\n';
}
return 0;
}
I'm getting correct answer for few test cases.The error i'm getting in ideone is
Runtime error time: 0 memory: 3100 signal:25
33628713
33628713
33628713
33628713
33628713
33628713
with infinite output when no input is given
I don't know what the logarithm is doing in your code. You somehow use it to determine when to stop dividing by powers of 5. It appears to be an approximation, and if you only get correct answers sometimes, then I expect that the approximation's inaccuracy is working against you.
You don't need the logarithm. You could simply stop the loop when you determine that there are no more factors of powers of 5 remaining. Think about how you could detect that using the values you've already calculated.
You don't need to approximate anything. A page at Purplemath explains and demonstrates how to calculate the number of trailing zeroes in a factorial number. Read the article and see whether you can recognize how the technique described there corresponds to parts of your code, and also notice how there are no logarithms involved on that page.

Online judge Rejecting My Answer

The Next Palindrome
The below code is the solution to this problem
A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output. Numbers are always displayed without leading zeros.
Input
The first line contains integer t, the number of test cases. Integers K are given in the next t lines.
Output
For each K, output the smallest palindrome larger than K.
Example
Input:
2
808
2133
Output:
818
2222
#include <iostream>
using namespace std;
int main()
{
long t;
cin>>t;
long a[t],k;
for(long i=0;i<t;++i)
{
cin>>k;
a[i]=k;
}
for(long i=0;i<t;++i)
{
long palin=0,num;
palin=a[i];
num=palin+1;
while(1)
{
long x=0,rev=0,ans=num;
do
{
x=ans%10;
rev=rev*10+x;
ans=ans/10;
}while(ans);
if(rev==num)
{
cout<<"\n"<<rev<<"\n";
break;
}
else
++num;
}
}
return 0;
}
The code is giving me expected output, I even made changes in the code making the variable K and t to LONG, should i make them long long instead of long, or is there any issue with my logic ...?
You can write a effective program by using a string instead of long. I have used it. Here I am giving the code:
#include<iostream>
using namespace std;
#include<string.h>
int main()
{
char s[80]; //you can take any big index instead 80
gets(s);
int a=0,l=strlen(s);
for(int i=0;i<l;i++) {
if(s[i]==s[l-i]) {
a++;
}
}
if(a==l) {
cout<<"Number is palindrome";
}
else {
cout<<"Number is not palindrome";
}
return(0);
}
Is the task really to handle integers up to 1,000,000 digits? Or is the input smaller than 1M?
"long" is guaranteed to be at least 32 bits long (so an unsigned long can hold integers [0, 4,294,967,295]. So if your input is < 1M, your safe with just regular long.
"long long" is guaranteed to be at least 64 bits long, so the range for unsigned long long is [0, 18x10^18]. Larger than 4M but still much smaller than 1M decimal digits.
Another issue with your code is the fact that it looks like your trying to dynamically allocate a stack array.
cin>>t;
long a[t],k;
You can't provide a variable as the array size. This is a very basic point an C++, and you must do one of the following:
Use a constant compile-time maximum size for the array (simplest solution).
#define A_MAX_SIZE 100
long a[A_MAX_SIZE];
Use a dynamic array (but then you must allocated and delete it later).
See link: http://www.cplusplus.com/doc/tutorial/dynamic/
Use an STL container that will take care of memory for you.
For example: http://www.cplusplus.com/reference/stl/vector/vector/

Prime number programs stops at 20,031'st prime, 225,149 for no apparent reason. No error message

Why does my program for finding primes work, but exit at the 20,031'st prime, which is 225,149? There is no error message and x-code claims that the program "ended with exit code" as it would normally do.
My question is not about the program per se, which appears to be working (finding primes), but what limit or calculation error I'm coming up against that's causing it to exit.
This loop is intentionally infinite, but it prints out to 225,149 as expected then stops and exits with no error. It just exits, as if it reached the end of a loop. I've tried putting a limit on iterations and bumped it up bit by bit to 10,000,0000,000 but it oddly stops a the same number, 225,149.
Is there a computation time bound that is exceeded or something else?
The last bit of output: the program outputs the a count of the primes from zero, then the prime.
20027) 225109
20028) 225119
20029) 225133
20030) 225143
20031) 225149
Program ended with exit code: 0
#include <iostream>
#include <cmath>
using namespace std;
//performs modulus and find remainder return remainder r to void primal
double fmodulus (double n, double d)
{
double r;
r= fmod(n, d);
return r;
}
//finds prime number using modulus double type modulus function fmod()
void primal()
{
int count=1;
double n=3.0, d=2.0;
for (int i= 0; i>=0; ++i)
{
double r;
r= fmodulus(n, d);
//if n==d then is prime nymber
if (n==d)
{
cout<<count<<") "<<n<<endl;
n++;
d=2.0;
count++;
}
//if remainder == 0 then not prime number
else if (r==0)
{
n++;
d=2.0;
}
//not prime so updates d of modulus increment by 1
else
{
d++;
}
}
}
int main(int argc, const char * argv[])
{
cout<<endl;
primal();
}
The problement si that i is incremented each time you make a test. In this case, you can easily reach 2 billion tests. And when i overflows, its value becomes negative, so the loop ends.
You can do 3 different things to solve this problem :
The first is to change the type of i to make it unsigned int or unsigned long long. Those types are always positive, and your loop will never end. The difference is only that an unsigned long long is written on 64 bits instead of 32.
The second way is to change the condition in your loop ; if you want it to be infinite, you can simply use 1. This is the general true condition.
The last way is to change your program, inserting a second loop inside the first to ensure that a different number is tested at each iteration.
Eventually the int i will overflow. Signed integer overflow is undefined behavior so the compiler can do whatever it wants.
Usually it will just overflow to INT_MIN, which is negative so your loop ends.
Try making i be a long and print its value to monitor it.

Error while solving Project Euler sum number 3 in C++

This is my code :
#include <iostream>
using namespace std;
int main()
{
long int x = 1;
long int res;
while (x<600851475143)
{
x++;
if(600851475143%x==0)
{
res=x;
cout<<x<<"\n";
}
}
}
I don't know whats wrong with it but it gives me this output :
839
1471
6857
59569
104441
486847
1234169
5753023
10086647
87625999
408464633
716151937
-716151937
-408464633
-87625999
-10086647
-5753023
-1234169
-486847
-104441
-59569
-6857
-1471
-839
-71
-1
Floating point exception
Process returned 136 (0x88) execution time : 156.566 s
Press ENTER to continue.
and when i substitute 600851475143 with 13195 [ which was in the example ]...
it works fine...and gives me this output :
5
11
55
11149
Process returned 0 (0x0) execution time : 0.005 s
Press ENTER to continue.
I don't know what i am doing wrong... :/
Perhaps my previous program didn't run properly...i tried it with int in the beginning and then changed it to long int...No difference...
Negative values are due to overflow. Start by using unsigned integers instead of signed integers. In addition to that, in 32 bit computers, long int and int types are both 32 bits.
unsigned long long int x = 1;
unsigned long long int res;
Also, you could emphasize the fact that those constants are unsigned
while (x<600851475143U)
{
x++;
if(600851475143U%x==0)
{
res=x;
cout<<x<<"\n";
}
}
When your positive number suddenly turns negative after ++, it's a sure sign of integer overflow. You need to pick a data type that is capable of holding larger integers, e.g. long long.
On a side note, your algorithm is not searching for the largest prime factor, as required in the problem. It searches for the largest factor, which is not necessarily a prime one.
By the way, if you can prove that stopping the search upon reaching the square root of the number being factored is correct, you could speed up your program a great deal.
Your variable types can't hold 12-figure numbers. Typical unsigned long int can store from 0 to 4,294,967,295, for signed - −2,147,483,648 to 2,147,483,647.
try using an unsigned long long, it should store at least 18,446,744,073,709,551,615 (which number I can't even imagine).
The code below will show all the prime factors of a number entered by user.But 600851475143 is a too much big number to find its prime factors. Modify this program to see 600851475143's prime factors and also modify it to find out the greatest prime factor of them. I have learned c++ for two months only, so i can help you this much only.All the best.
#include<iostream.h>
#include<conio.h>
class primefactor
{
unsigned long int a;
public:
void factor();
};
void primefactor::factor()
{
cout<<"Enter any number to see its prime factors";
cin>>a;
int count=0;
int count1=0;
for(unsigned long int loop1=a;loop1>=1;loop1--)
{
if(a%loop1==0)
{
for(unsigned long int loop=loop1;loop>=1;loop--)
{
if(loop1%loop==0)
{
count++;
}
}
if(count==2)
{
count1++;
cout<<loop1<<"\t";
}
}
count=0;
}
cout<<"\n"<<"There are"<<count1<<"\t"<<"prime factors";
}
void main()
{
primefactor k;
clrscr();
k.factor();
getch();
}