Skip to main content

Posts

Showing posts from August, 2020

Factorial of a large number

  In computers, variables are stored in memory locations. But the size of the memory location is fixed, so when we try to find the factorial of some greater value like 15! or 20! the factorial value exceeds the memory range and returns wrong results. For calculation of large numbers, we have to use an array to store results. In each element of the array, is storing different digits of the result. But here we cannot multiply some number with the array directly, we have to perform manual multiplication process for all digits of the result array. Video Tutorial: https://youtu.be/LCDSigIDqnw?t=15 Input and Output Input: A big number: 50 Output: Factorial of given number is: 30414093201713378043612608166064768844377641568960512000000000000 Algorithm multiply(x, multiplicand) Input:  The number x, and the large multiplicand as an array. Output:  Result after multiplication. Begin    carry := 0    for all digits i of multiplicand, do       prod := i*x+carry       i := prod mod 10       carry

Breaking The Summation Formula (Part 1)

 Q. f ( n ) =  - 1 + 2 - 3 + .. + ( - 1) n n .  Given n, find out f(n) Approach(1)- Bruteforce: 1. Calculation sum=n*(n+1)/2 2. loop[i=1,i=n : i+=2] odd+=i 3.ans=sum-2*odd Code: #include < bits / stdc ++. h > using namespace std ; int main (){   long long x ; cin >> x ; long long p =( x *( x + 1 ))/ 2 ; long long bad = 0 ; for ( long long i = 1 ; i <= x ; i += 2 ) bad += i ; cout << p - 2 * bad << endl ; } Approach(2)-Greedy: Basic: s=1+2+3+4+....+n Formula: sum=n*(n+1)/2= (n/2) + (n+1).2

Application of Modular Arithmetic

  Q: If you have x,y,n. and you have to find a number k between 0<=n so that, k%x=y Approach1(Bruteforce): 1.Check if n%x==y print n 2.if n%x!=y then loop until n%x==y then print n.  Code: #include < bits / stdc ++. h > using namespace std ; int main (){   int t ; cin >> t ; while ( t --) { int x , y , n ; cin >> x >> y >> n ; if ( n % x == y ) cout << n << endl ; else { while ( n % x != y ) { n --; } cout << n << endl ; } } } Approach2(Greedy): Time Complexity: O(n) let assume, k=p'*x+y now, p'=(k-y)/x ; 0<=k<=