# Tips & Tweaks when programming Math !

In this post,I am going to tell you some tips and tricks which you should know & you can implement in your codes if required.You dont need to require long codes for short tasks.

To check if a number is power of 2,just calculate log2(n) and if it is an integer,it is a power of 2 else it is not.

Number of digits in a number is ceil[log(n)]. This formula is used to calculate the number of digits in n!.

nCr denotes the number of ways of choosing ‘r’ objects from ‘n’ objects.
nCr=(n-1)C(r) + (n-1)C(r-1)

To find the gcd/hcf of two numbers,you should use Euclid’s algorithm.
Program in C —

gcd(int a,int b)
{
if(b==0) return a;
else gcd(b,a%b);
}

LCM of two numbers= (a*b)/gcd(a,b)

To find the number which occurs odd number of times in a list given that all other numbers appear even number of times-
XOR all the numbers and the result gives you the element which occurs odd number of times.

To check if the nth bit of a number is on/off.AND the number with 2 to the power i.If the result is 0,then it is OFF.

To find the nth Fibonacci number-

fib(n)
{
if(n==0) return 0;
if(n==1) return 1;
return f(n-1)+f(n-2);
}

Given a list of numbers from 1 to n and a number is missing,you have to find the missing number.
Method 1-
Find the sum of all given numbers and subtract it from n*(n+1)/2,you get the unknown number.
Method 2-
XOR all the numbers from 1 to n.Let the result be A1.
XOR all the given numbers.Let the result be A2.
XOR A1 and A2.The result gives the unknown number.

You may use these HTML tags and attributes: `<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> `