Monday, 12 June 2023

Count of digits in factorial

 To count the digits in a factorial we must seek some optimization as you might also understand that getting all the product and storing them could lead to wastage of storage.

So what to do?

Lets see this :




As we can see by doing this we can get count of numbers in the range, like 

1-9 = 1 digit

10-99 = 2 digit

100-999 = 3 digit

and so on.

we got the formula = floor[log(x)] + 1

but wait we need for factorial not a single digit right?

like factorial of  5! = 1 * 2 * 3 * 4 * 5

                              = 120 
and we need to check for 120 not 1,2,3,4,5. so what to do?

well 5! can be written as 1 * 2 * 3 * 4 * 5 so no worries. 

so lets put that in the equation.

floor[log(x)] = floor[log(120)] = floor[log(1*2*3*4*5)]


Now from the log formula we know we can add these simply. 

floor[ log(1) + log(2) + log(3) + log(4) + log(5) ] + 1

There you have it!!!

Now code :






Sunday, 4 June 2023

Prime Optimized

 Know if the number is Prime Or Not Most Optimized Way.

we know by dividing till root N but that's not the best approach. 
We can move even further beyond by this technique to increase its efficiency by 3 times.

first we put checks of divisible by 2 and 3
and if not then further go on iterating by increasing the iterator by 6. Why? bcz 2 and 3 would cover up for all the numbers in between.
and another condition inside checking for number divided by iterator+2 for cases like 7,13, etc

Code :



LCM optimized

 Optimized solution to find LCM

We can use the formula :
A * B = GCD(A,B) * LCM(A,B)
(simple pair hai ye....)
As,
LCM(A,B) = (A*B) / GCD(A,B)

What is GCD?
=>  Here

Code :



GCD/HCF optimized

How to calculate GCD/HCF with optimization.

Step 1 : Calculate Remainder between A and B.

Step 2 : Change A with B and B with remainder obtained

Step 3 : Do this recursively till we get B as 0

 

Note : A > B, if its not the case then change B and A.

Code :










Count of digits in factorial

 To count the digits in a factorial we must seek some optimization as you might also understand that getting all the product and storing the...