Binary math - math

If I know the number number y and know that 2^x=y, how do I compute x?

Base 2 logarithm function:
log2(y)
which is equivalent to:
log(y) / log(2)
for arbitrary base.

And in case you don't have a log function handy, you can always see how many times you must divide y by 2 before it becomes 1. (This assumes x is positive and an integer.)

If you are sure that it is a power of 2, then you can write a loop and right shift the number until you get a 1. The number of times the loop ran will be the value of x.
Example code:
int power(int num)
{
if(0 == num)
{
return 0;
}
int count = 0;
do
{
++count;
num = num >> 1;
}while(! (num & 1) && num > 0);
return count;
}

If x is a positive integer, then, following code will be more efficient..
unsigned int y; // You know the number y for which you require x..
unsigned int x = 0;
while (y >>= 1)
{
x++;
}
x is the answer!

Related

FINDING total number of paths using backtracking

I'm trying to count total paths in a 20x20 grid(ProjectEuler #15) using backtracking.I've played around with it but the answer is always None. Any help would be appreciated(I know it can be solved using recursion or memoization but i want to solve it using backtracking)
def isvalid(maze,n,x,y):
if x<0 or y<0 or x>n or y>n :
return False
else: return True
def countPaths(maze,x,y,n,used,count):
if x==n-1 or y==n-1:
count+=1
return
if isvalid(maze,n,x,y):
used[x][y]=True
if (x+1<n and used[x+1][y]==False):
countPaths(maze,x+1,y,n,used,count)
if (x-1>0 and used[x-1][y]==False):
countPaths(maze,x-1,y,n,used,count)
if (y+1<n and used[x][y+1]==False):
countPaths(maze,x,y+1,n,used,count)
if (y-1>0 and used[x][y-1]==False):
countPaths(maze,x,y-1,n,used,count)
used[x][y]=False
return
Since in the base case, you are only returning 1 whenever end of row or column occurs it would yield wrong answer.
You should increment a counter signifying the number of times you are able to reach the final [n-1][n-1] i.e rightmost bottom cell.
bool isValid(int x, int y)
{
if (x < 0 || x >= n || y < 0 || y >= n)
return false;
return true;
}
void countPaths(int x, int y)
{
// cout << x << y << endl;
if (x == n - 1 && y == n - 1)
{
paths++;
return;
}
if (isValid(x, y))
{
visited[x][y] = true;
countPaths(x, y + 1);
countPaths(x + 1, y);
}
return;
}
Keeping paths & visited as global variables , I implemented the above approach.
For n=2 (1+1): 2
For n=3 (2+1): 6
For n=4 (3+1): 20
For n=5 (4+1): 70
however, this approach would not be viable for n=20.
I would suggest trying Dynamic Programming as it would simplify the process!

Frame the solution using Dynamic programming

Given a bag with a maximum of 100 chips,each chip has its value written over it.
Determine the most fair division between two persons. This means that the difference between the amount each person obtains should be minimized. The value of a chips varies from 1 to 1000.
Input: The number of coins m, and the value of each coin.
Output: Minimal positive difference between the amount the two persons obtain when they divide the chips from the corresponding bag.
I am finding it difficult to form a DP solution for it. Please help me.
Initially I had to tried it as a Non DP solution.Actually I havent thought of solving it using DP. I simply sorted the value array. And assigned the largest value to one of the person, and incrementally assigned the other values to one of the two depending upon which creates minimum difference. But that solution actually didnt work.
I am posting my solution here :
bool myfunction(int i, int j)
{
return(i >= j) ;
}
int main()
{
int T, m, sum1, sum2, temp_sum1, temp_sum2,i ;
cin >> T ;
while(T--)
{
cin >> m ;
sum1 = 0 ; sum2 = 0 ; temp_sum1 = 0 ; temp_sum2 = 0 ;
vector<int> arr(m) ;
for(i=0 ; i < m ; i++)
{
cin>>arr[i] ;
}
if(m==1 )
{
if(arr[0]%2==0)
cout<<0<<endl ;
else
cout<<1<<endl ;
}
else {
sort(arr.begin(), arr.end(), myfunction) ;
// vector<int> s1 ;
// vector<int> s2 ;
for(i=0 ; i < m ; i++)
{
temp_sum1 = sum1 + arr[i] ;
temp_sum2 = sum2 + arr[i] ;
if(abs(temp_sum1 - sum2) <= abs(temp_sum2 -sum1))
{
sum1 = sum1 + arr[i] ;
}
else
{
sum2 = sum2 + arr[i] ;
}
temp_sum1 = 0 ;
temp_sum2 = 0 ;
}
cout<<abs(sum1 -sum2)<<endl ;
}
}
return 0 ;
}
what i understand from your question is you want to divide chips in two persons so as to minimize the difference between sum of numbers written on those.
If understanding is correct, then potentially you can follow below approach to arrive at solution.
Sort the values array i.e. int values[100]
Start adding elements from both ends of array in for loop i.e. for(i=0; j=values.length;i<j;i++,j--)
Odd numbered iteration sum belongs to one person & even numbered sum to other person
run the loop till i < j
now, the difference between two sums obtained in odd & even iterations should be minimum as array was sorted earlier.
If my understanding of the question is correct, then this solution should resolve your problem.
Reflect as appropriate.
Thanks
Ravindra

Convert a natural number to binary using recursion

I have to convert a natural number to binary but using recursion. I did but without recursion:
int main (){
int n,pot,bin;
printf("Digite o Numero:\n");
scanf("%d",&n);
pot=1;
bin=0;
while (n>0){
bin+=(n%2)*pot;
pot*=10;
n= n/2;
}
printf ("%d",bin);
getch();
return 0;
}
something like (ASSUMING n is positive!):
void getBin(uint n, int pot, int* bin) {
*bin += (n%2)*pot;
n /= 2;
if (n <= 0) {
return;
}
getBin(n, pot * 10, bin);
}
Just to be on the safe side this does not convert a positive number to binary. It creates a number that, when displayed in base 10, looks like the argument in base 2.
A better solution would be to convert the number to char* in a given base.
int getBin(int n) {
return getBinHelper(n, 1, 0);
}
int getBinHelper(int n, int e, int acc) {
return n == 0 ?
acc :
getBinHelper( n/2, e*10, n&1 ? acc+e : acc);
}

Codility K-Sparse Test **Spoilers**

Have you tried the latest Codility test?
I felt like there was an error in the definition of what a K-Sparse number is that left me confused and I wasn't sure what the right way to proceed was. So it starts out by defining a K-Sparse Number:
In the binary number "100100010000" there are at least two 0s between
any two consecutive 1s. In the binary number "100010000100010" there
are at least three 0s between any two consecutive 1s. A positive
integer N is called K-sparse if there are at least K 0s between any
two consecutive 1s in its binary representation. (My emphasis)
So the first number you see, 100100010000 is 2-sparse and the second one, 100010000100010, is 3-sparse. Pretty simple, but then it gets down into the algorithm:
Write a function:
class Solution { public int sparse_binary_count(String S,String T,int K); }
that, given:
string S containing a binary representation of some positive integer A,
string T containing a binary representation of some positive integer B,
a positive integer K.
returns the number of K-sparse integers within the range [A..B] (both
ends included)
and then states this test case:
For example, given S = "101" (A = 5), T = "1111" (B=15) and K=2, the
function should return 2, because there are just two 2-sparse integers
in the range [5..15], namely "1000" (i.e. 8) and "1001" (i.e. 9).
Basically it is saying that 8, or 1000 in base 2, is a 2-sparse number, even though it does not have two consecutive ones in its binary representation. What gives? Am I missing something here?
Tried solving that one. The assumption that the problem makes about binary representations of "power of two" numbers being K sparse by default is somewhat confusing and contrary.
What I understood was 8-->1000 is 2 power 3 so 8 is 3 sparse. 16-->10000 2 power 4 , and hence 4 sparse.
Even we assume it as true , and if you are interested in below is my solution code(C) for this problem. Doesn't handle some cases correctly, where there are powers of two numbers involved in between the two input numbers, trying to see if i can fix that:
int sparse_binary_count (const string &S,const string &T,int K)
{
char buf[50];
char *str1,*tptr,*Sstr,*Tstr;
int i,len1,len2,cnt=0;
long int num1,num2;
char *pend,*ch;
Sstr = (char *)S.c_str();
Tstr = (char *)T.c_str();
str1 = (char *)malloc(300001);
tptr = str1;
num1 = strtol(Sstr,&pend,2);
num2 = strtol(Tstr,&pend,2);
for(i=0;i<K;i++)
{
buf[i] = '0';
}
buf[i] = '\0';
for(i=num1;i<=num2;i++)
{
str1 = tptr;
if( (i & (i-1))==0)
{
if(i >= (pow((float)2,(float)K)))
{
cnt++;
continue;
}
}
str1 = myitoa(i,str1,2);
ch = strstr(str1,buf);
if(ch == NULL)
continue;
else
{
if((i % 2) != 0)
cnt++;
}
}
return cnt;
}
char* myitoa(int val, char *buf, int base){
int i = 299999;
int cnt=0;
for(; val && i ; --i, val /= base)
{
buf[i] = "0123456789abcdef"[val % base];
cnt++;
}
buf[i+cnt+1] = '\0';
return &buf[i+1];
}
There was an information within the test details, showing this specific case. According to this information, any power of 2 is considered K-sparse for any K.
You can solve this simply by binary operations on integers. You are even able to tell, that you will find no K-sparse integers bigger than some specific integer and lower than (or equal to) integer represented by T.
As far as I can see, you must pay also a lot of attention to the performance, as there are sometimes hundreds of milions of integers to be checked.
My own solution, written in Python, working very efficiently even on large ranges of integers and being successfully tested for many inputs, has failed. The results were not very descriptive, saying it does not work as required within question (although it meets all the requirements in my opinion).
/////////////////////////////////////
solutions with bitwise operators:
no of bits per int = 32 on 32 bit system,check for pattern (for K=2,
like 1001, 1000) in each shift and increment the count, repeat this
for all numbers in range.
///////////////////////////////////////////////////////
int KsparseNumbers(int a, int b, int s) {
int nbits = sizeof(int)*8;
int slen = 0;
int lslen = pow(2, s);
int scount = 0;
int i = 0;
for (; i < s; ++i) {
slen += pow(2, i);
}
printf("\n slen = %d\n", slen);
for(; a <= b; ++a) {
int num = a;
for(i = 0 ; i < nbits-2; ++i) {
if ( (num & slen) == 0 && (num & lslen) ) {
scount++;
printf("\n Scount = %d\n", scount);
break;
}
num >>=1;
}
}
return scount;
}
int main() {
printf("\n No of 2-sparse numbers between 5 and 15 = %d\n", KsparseNumbers(5, 15, 2));
}

What is the most efficient way to calculate the least common multiple of two integers?

What is the most efficient way to calculate the least common multiple of two integers?
I just came up with this, but it definitely leaves something to be desired.
int n=7, m=4, n1=n, m1=m;
while( m1 != n1 ){
if( m1 > n1 )
n1 += n;
else
m1 += m;
}
System.out.println( "lcm is " + m1 );
The least common multiple (lcm) of a and b is their product divided by their greatest common divisor (gcd) ( i.e. lcm(a, b) = ab/gcd(a,b)).
So, the question becomes, how to find the gcd? The Euclidean algorithm is generally how the gcd is computed. The direct implementation of the classic algorithm is efficient, but there are variations that take advantage of binary arithmetic to do a little better. See Knuth's "The Art of Computer Programming" Volume 2, "Seminumerical Algorithms" § 4.5.2.
Remember
The least common multiple is the least whole number that is a multiple of each of two or more numbers.
If you are trying to figure out the LCM of three integers, follow these steps:
**Find the LCM of 19, 21, and 42.**
Write the prime factorization for each number. 19 is a prime number. You do not need to factor 19.
21 = 3 × 7
42 = 2 × 3 × 7
19
Repeat each prime factor the greatest number of times it appears in any of the prime factorizations above.
2 × 3 × 7 × 19 = 798
The least common multiple of 21, 42, and 19 is 798.
I think that the approach of "reduction by the greatest common divider" should be faster. Start by calculating the GCD (e.g. using Euclid's algorithm), then divide the product of the two numbers by the GCD.
Best solution in C++ below without overflowing
#include <iostream>
using namespace std;
long long gcd(long long int a, long long int b){
if(b==0)
return a;
return gcd(b,a%b);
}
long long lcm(long long a,long long b){
if(a>b)
return (a/gcd(a,b))*b;
else
return (b/gcd(a,b))*a;
}
int main()
{
long long int a ,b ;
cin>>a>>b;
cout<<lcm(a,b)<<endl;
return 0;
}
First of all, you have to find the greatest common divisor
for(int i=1; i<=a && i<=b; i++) {
if (i % a == 0 && i % b == 0)
{
gcd = i;
}
}
After that, using the GCD you can easily find the least common multiple like this
lcm = a / gcd * b;
I don't know whether it is optimized or not, but probably the easiest one:
public void lcm(int a, int b)
{
if (a > b)
{
min = b;
max = a;
}
else
{
min = a;
max = b;
}
for (i = 1; i < max; i++)
{
if ((min*i)%max == 0)
{
res = min*i;
break;
}
}
Console.Write("{0}", res);
}
Here is a highly efficient approach to find the LCM of two numbers in python.
def gcd(a, b):
if min(a, b) == 0:
return max(a, b)
a_1 = max(a, b) % min(a, b)
return gcd(a_1, min(a, b))
def lcm(a, b):
return (a * b) // gcd(a, b)
Using Euclidean algorithm to find gcd and then calculating the lcm dividing a by the product of gcd and b worked for me.
int euclidgcd(int a, int b){
if(b==0)
return a;
int a_rem = a % b;
return euclidgcd(b, a_rem);
}
long long lcm(int a, int b) {
int gcd=euclidgcd(a, b);
return (a/gcd*b);
}
int main() {
int a, b;
std::cin >> a >> b;
std::cout << lcm(a, b) << std::endl;
return 0;
}
Take successive multiples of the larger of the two numbers until the result is a multiple of the smaller.
this might work..
public int LCM(int x, int y)
{
int larger = x>y? x: y,
smaller = x>y? y: x,
candidate = larger ;
while (candidate % smaller != 0) candidate += larger ;
return candidate;
}
C++ template. Compile time
#include <iostream>
const int lhs = 8, rhs = 12;
template<int n, int mod_lhs=n % lhs, int mod_rhs=n % rhs> struct calc {
calc() { }
};
template<int n> struct calc<n, 0, 0> {
calc() { std::cout << n << std::endl; }
};
template<int n, int mod_rhs> struct calc<n, 0, mod_rhs> {
calc() { }
};
template<int n, int mod_lhs> struct calc <n, mod_lhs, 0> {
calc() { }
};
template<int n> struct lcm {
lcm() {
lcm<n-1>();
calc<n>();
}
};
template<> struct lcm<0> {
lcm() {}
};
int main() {
lcm<lhs * rhs>();
}
Euclidean GCD code snippet
int findGCD(int a, int b) {
if(a < 0 || b < 0)
return -1;
if (a == 0)
return b;
else if (b == 0)
return a;
else
return findGCD(b, a % b);
}
Product of 2 numbers is equal to LCM * GCD or HCF. So best way to find LCM is to find GCD and divide the product with GCD. That is, LCM(a,b) = (a*b)/GCD(a,b).
There is no way more efficient than using a built-in function!
As of Python 3.8 lcm() function has been added in math library. And can be called with folowing signature:
math.lcm(*integers)
Returns the least common multiple of the specified integer arguments. If all arguments are nonzero, then the returned value is the smallest positive integer that is a multiple of all arguments. If any of the arguments is zero, then the returned value is 0. lcm() without arguments returns 1.
Extending #John D. Cook answer that is also marked answer for this question. ( https://stackoverflow.com/a/3154503/13272795), I am sharing algorithm to find LCM of n numbers, it maybe LCM of 2 numbers or any numbers. Source for this code is this
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
// Returns LCM of array elements
ll findlcm(int arr[], int n)
{
// Initialize result
ll ans = arr[0];
// ans contains LCM of arr[0], ..arr[i]
// after i'th iteration,
for (int i = 1; i < n; i++)
ans = arr[i] * ans/gcd(arr[i], ans);
return ans;
}
Since we know the mathematic property which states that "product of LCM and HCF of any two numbers is equal to the product of the two numbers".
lets say X and Y are two integers,
then
X * Y = HCF(X, Y) * LCM(X, Y)
Now we can find LCM by knowing the HCF, which we can find through Euclidean Algorithm.
LCM(X, Y) = (X * Y) / HCF(X, Y)
Hope this will be efficient.
import java.util.*;
public class Hello {
public static int HCF(int X, int Y){
if(X == 0)return Y;
return HCF(Y%X, X);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int X = scanner.nextInt(), Y = scanner.nextInt();
System.out.print((X * Y) / HCF(X, Y));
}
}
Yes, there are numerous way to calculate LCM such as using GCD (HCF).
You can apply prime decomposition such as (optimized/naive) Sieve Eratosthenes or find factor of prime number to compute GCD, which is way more faster than calculate LCM directly. Then as all said above, LCM(X, Y) = (X * Y) / GCD(X, Y)
I googled the same question, and found this Stackoverflow page,
however I come up with another simple solution using python
def find_lcm(numbers):
h = max(numbers)
lcm = h
def check(l, numbers):
remainders = [ l%n==0 for n in numbers]
return all(remainders)
while (check(lcm, numbers) == False):
lcm = lcm + h
return lcm
for
numbers = [120,150,135,225]
it will return 5400
numbers = [120,150,135,225]
print(find_lcm(numbers)) # will print 5400

Resources