5. Maths- part 1

                                        1.) Extraction of digits-

d=(n%10)   --->  n= (n/10), while n>0

---------------------------------------------------------------------------------

                                      2.) Reverse of number-


int rev = 0
rev = ( rev*10 + Last digit )

check for overflow/ underflow before updating ans-
  if ((ans >= INT_MAX / 10) || (ans < INT_MIN / 10)) {
     return 0; 
   }

----------------------------------------------------------------------------------

                                             3.) Palindrome-⭐

reverse = original
single digit numbers are already palindrome

---------------------------------------------------------------------------------

4.) Armstrong number-

just write this after finding digit :-
sum = sum + pow(d,K)

where, K = no. of digits = 1+log10(n)

----------------------------------------------------------------------------------

5.) Divisors-
1. (i) is a divisor of (n), if (n%i) == 0
2.  divisors occur in pairs, i.e., if (i) is a divisor of n then, (n/i) is also a divisor of n,
3. hence we reduce complexity from N to sqrt(N) for finding divisors
4.  PRIME NUMBER- it has only two divisors: 1 and no. itself
5. remember an additional check for i = n/i , so you don't overcount

below is code for checking if a number is prime or not:-⭐

-----------------------------------------------------------------------------------
                           
6.)                                            GCD/ HCF:
  
Method 1
- highest factor which is common to both.
- Algo: find factors of smaller one and check for each factor if it divides both the given numbers.
- Complexity- O( min[a, b] )
- instead of going from 1 to min(a, b) we will go in reverse, to optimize it further.
----------------------------
int x = 12;
int y = 28;

for( int i=x; i>=1; i-- ){

      if( x%i=0 & y%i=0 ){
        
        print(gcd is i) ;
        break;
      
    }

}
-----------------------------------------------------------
                                  Method 2- log( min[a, b] )
THEOREM:-
gcd( a, b ) = gcd (a-b, b)
when done repeatedly gives us,
gcd( a, b ) = gcd ( a%b, b)

we will apply this, till one of them becomes zero, as then the other one is our answer.
------------------------------------------------------------


------------------------------------------------------------------------------

7.)  Finding LCM⭐

Lcm= (a*b) / gcd(a,b);

------------------------------------------------------------------------------

Comments

Popular posts from this blog

30.) DP on subsequences

19. Strings (LB)

32. Binary Trees-2 (bfs/dfs med problems)