When the number is small directly check its divisibility by 3 by dividing it . works fine but if number is large this technique is no more best technique to check divisibility ..
Hope you enjoy this technique ..
YOu can develop your algorithm and make it public .. contact us query.b2cs@gmail.com
and you can post your content & algorithm on this blog ..
Other way is by checking divisibility of sum of its digit . but this technique is also not effective because to find each digit we need to divide again & again by 10.
But there exist a much faster way to check this .
Now think about binary representation of a number in binary . Since we generally ignore property of number in binary that's why you did't find this till now .
Concept :
find out number of set odd position bit from right (let say it odd_set ) & find number of set even position bit from right (let say is even_set ). set bit means has value 1.
Now if difference of odd_set & even_set divisible by 3 than it is divisible otherwise not divisible by 3 .
& treat 0 & 1 as special case ..
C++ Code :
- /*
- to check divisibility of a number by 3
- ..Most efficent way to check if number is large;
- */
- /*
- **************************************** CONCEPT **********************************
- it is based on concept that
- (total set bit at odd position from right - total set bit at even position )
- is divisible by 3 than Number is divisible by 3
- ************************************************************************************
- */
- #include<iostream>
- #include<math.h>
- using namespace std;
- int IsDivBy3(int n) //function def
- {
- int even=0,odd=0;
- /****************special case****************/
- if(n==0) return 1;
- else if(n==1) return 0;
- /******************************************/
- if(n<0) n=-n; //to make number positive;
- while(n>0)
- {
- if(n & 1) //and operation
- odd++;
- n=n>>1; //right sift in binary by 1 ex: 1011 -> 011
- if(n & 1) //and operation
- even++;
- n=n>>1; //right sift in binary by 1 ex: 1011 -> 011
- }
- if((abs(even-odd))%3==0)
- return(1);
- else
- return(0);
- }
- main()
- {
- int n;
- cout<<"enter number to check divisibility by 3 : ";
- cin>>n;
- if(IsDivBy3(n)) //call this function to check it return 1 if divisible otherwise 0
- cout<<"divisible";
- else
- cout<<"Not divisible";
- return 0;
- }
Hope you enjoy this technique ..
YOu can develop your algorithm and make it public .. contact us query.b2cs@gmail.com
and you can post your content & algorithm on this blog ..
No comments:
Post a Comment
THANKS FOR UR GREAT COMMENT