Numbers Basicsss
Numbers Basicsss
Approach: We can reverse the original number and compare the original with the reversed number.
If both are the same, the number qualifies as a palindrome number.
Say the input number is X. Declare a variable Y to store the reverse and initialize it to 0. Make a copy
of X, say dummy that will be used later for comparison.
At every step extract the last digit using the % operator. Suppose X%10 = d.
We will append this last digit, d to Y using a formula 10*Y+d.
The last digit of X has been used. Discard it using X/10.
Repeat these steps for the remaining digits. After every iteration, the size of X will shrink by one
digit. Terminate the iteration when X = 0 meaning no new digits are left to be reversed.
The reversed number Y is compared with the dummy variable since X was destroyed while iteration.
If Y equals dummy print “Palindrome Number” otherwise “Not Palindrome Number”. Time
Complexity: O(logN) for reversing N digits of input integer.
Palindrome: We will reverse the number, if it is equal to the given number then it
is palindrome otherwise it is not.
Approach:
Use a for loop and pass every element to the palindrome function.
Now make a palindrome function which takes an integer as a parameter.
Reverse the given number.
If the reversed number is equal to the given number then print it.
Reversing a number:
Running the for loop from 2 to the square root of the number.
And then checking if the number is divisible by the numbers from 2 to its square
root.
Then, If the remainder is zero, that means it is divisible and hence not a prime
number.
If the loop runs till square root and none of the numbers divided it completely. So
it is the Prime number.
n=153
sum=0
In the First iteration, extract digit 3 from 153 and cube it which becomes 27, add it to sum=
0+27=27 which becomes 27 now
In Second iteration , extract digit 5 from 15 and cube it which becomes 125 , add it to sum = 27
+125 = 152 which becomes 152 now
In Third iteration , extract digit 1 from 1 and cube it which becomes 1 , add it to sum = 152 + 1 =
153 which becomes 153 now.
The original Number was 153 and the sum of cubes = 153.
We can find the proper divisors of a given number. If their sum is equal to the
given number then it is a perfect number.
Approach:
We initialise a sum to 0.
We can set a loop to iterate from 1 to n-1.
In every iteration we check if n is divisible by i, if it is we add it to our sum.
After the loop is over, we check whether the given number is equal to our
sum, if it is then we the given number is a perfect number, otherwise not.
Intuition: If we can prove that the given number is divisible by 2 then it will be
even, otherwise it will be odd.
Approach:
Intuition: As we know that bitwise operations are generally faster than normal
operations so we should prefer it over normal operations.
If we can get the last bit of any number then we can say that it is even or odd.
Approach:
Approach:
Intuition: The signed right shift operator ‘>>’ uses the sign bit to fill the trailing positions. For
example, if the number is positive then 0 will be used to fill the trailing positions and if the number is
negative then 1 will be used to fill the trailing positions.
Hence we can say that if a number is positive and we right shift it by 31, then we will get zero, and if
the number is negative then we will get -1.
For eg: a = 5 , b = -6
a>>31
b>>31
Approach:
This approach is a lot simpler than the parameterized recursion. We can visualize
the sum of n natural numbers in the following way as shown below:
sumOfNaturalNumbers(N) = N + sumOfNaturalNumbers(N-1);
The Sum of N natural numbers would just be the Nth integer added to the Sum of
(N-1) natural numbers. The base case can be visualized as if n decreases to 0, then
we return 0 because the sum of 0 natural numbers is 0 only. Here, we’ve just
broken the problem into 2 subparts and the answers of both these subparts would
be added and stored in the Sum(n) function which would then be printed at last.
Find Sum of AP Series
Solution 1: Using Loops
Approach: This approach consists of simply adding elements by moving them for
a loop. We create a sum variable and add the terms one by one to get the sum of
the A.P. Series.
For Example,
Approach: Check if the year is divisible by 4 or 400 but not by 100 then it is a
leap year
Approach: If a year is divisible by 4 or 400 but not by 100 then it is a leap year.
Approach:
Take an array say fib of size n+1.The 0th term and 1st term are 0 and 1
respectively.So fib(0)=0 and fib(1)=1.
Now iterate from 2 to n and calculate fib(n).fib(n)=fib(n-1) + fib(n-2).
Then print fib(0) + fib(1) + …………fib(n).
Intuition: For calculating the ith term we only need the last and second last term
i.e (i-1)th and (i-2)th term, so we don’t need to maintain the whole array.
Approach:
Take two variables last and secondLast for storing (i-1)th and (i-2)th term.
Now iterate from 2 to n and calculate the ith term. ith term is last +
secondLast term.
Then update secondLast term to the last term and the last term to ith term as
we iterate.
Solution 3
Intuition:
In this approach, instead of printing the Fibonacci series till N, we’re going to print the Nth Fibonacci
number using functional recursion with multiple function calls.
One may wonder how multiple-function calls work. Let’s understand through an illustration below:
Similar kinds of multiple-function calls would be used in implementing the Fibonacci series where
any Nth Fibonacci number can be written as a sum of (N-1)th and (N-2)th Fibonacci numbers. So, the
function result would look like this:
Approach:
Similar to all the recursion problems we’ve seen before, we need a base case in this problem
too in order for recursion to not go infinitely. Here, we notice that the Fibonacci series start
from N = 1, where we initialize its value as 1.
Assume Fibonacci(0) = 0. So, Fibonacci(2) = 1+0 = 1 as the Nth Fibonacci number is the sum
of the previous two Fibonacci numbers.
Similarly, we call Fibonacci(N-1) and Fibonacci(N-2) and return their sum. Both the function
calls Fibonacci(N-1) and Fibonacci(N-2) would be computed individually one by one until
the base condition is reached for both and then they return back to the main function.
Approach:
Since the factorial of X will be the product of the number itself and all its
preceding numbers we can run loop i, from 1 to X. In every iteration current i, is
multiplied with the product so far.
Calculate the Power of a Number : Binary
Exponentiation
Solution 1: Naive approach
Approach:
Take a variable ans to store final answer.Initially let the value of ans be 1.
Multiply ans with n for k times.
Print ans.
Intuition: While calculating (n^k), binary exponentiation relies on whether n is even or odd.
If k is even (nk) can be written as (n2)k/2. As we can see that computation steps were reduced from k to
k/2 in just one step.
Approach:
Intuition: We can simply use a for loop from 1 to n and check for every element
that n is divisible by it or not, if it is then we will print it otherwise just skip it.
Approach:
Intuition: When we thoroughly see the factors of a natural number, they always lie in pairs. For if ‘n’
is divisible by any number ‘i’ then it will also be divisible by its quotient of n/i.
Approach:
Intuition:
Approach :
We will be using a For loop where i will start from 2 and go on till n-1
For each value of i, we will divide while N % i ==0 and change N to N/i,
and till the while loop goes on we will print the i value.
Intuition: If you consider a number N, then you can notice that during factorization. Once N is
reduced to a Prime Number, we know that the only factor possible is itself now and we can stop
evaluating afterward.
Ans: If a number N doesn’t have any factor till the square root of N, then it’s a Prime Number.
Proof : Let’s say P = sqrt(N) where sqrt() stands for square root .
Then P*P == N . Now , if n is composite number ,
Hence we can conclude that min(Q, R) <= P . Hence we can search till P and find at least 1 factor to
prove that N is not a Prime Number.
Approach: Method will be the same as mentioned in Solution 1 with a slight change in the For Loop.
In Solution 1, we used to run loop till i<n, but now we will run For Loop till Square Root of N.
1. Inside the loop check if the last digit of the number is equal to last digit of
its square.
2. If it is not equal then return false.
3. Otherwise divide the number by 10 inorder to reduce it.
4. Now if the loop runs till the end then it is an Automorphic number and
return true.
Find GCD of two numbers
Solution 1: Brute force
Intuition: Simply traverse from 1 to min(a,b) and check for every number.
Approach:
Intuition: Gcd is the greatest number which is divided by both a and b.If a
number is divided by both a and b, it is should be divided by (a-b) and b as well.
Approach:
Intuition: Simply traverse from 1 to min(a,b) and check for every number.
Find gcd using brute force.
Traverse from 1 to min(a,b).
And check if i is divisible by both a and b.If yes store it in the answer.
Find the maximum value of i which divides both a and b.
To find lcm simply divide (a*b) by gcd of a and b.
Intuition: Gcd is the greatest number which is divided by both a and b.If a number
is divided by both a and b, it is should be divided by (a-b) and b as well.Using this
we can find gcd in log(min(a,b)) and hence lcm.
Approach:
Intuition: If the sum of digits is divisible by the number then it is called Harshad
number.
Approach:
Intuition: In solution1 we needed an extra variable temp to store the value of n, but if we use string
there won’t be any need for the extra variable.
Approach:
Approach:
Traverse from 1 to n.
Maintain a sum variable to store sum of all the divisors of n.
If i is a divisor of n then add it to the sum.
After the traversal is complete,if the sum is greater than 1,print “yes”,else
print “no”.
Note: Did you notice we get the last digit of a number when we perform a modulus
operation with a value of 10
Approach:
Approach:
Approach:
Maintain two variables num and den to store numerator and denominator.
We need to find n! and (n-r)!.
Traverse from 1 to n and multiple i by num to find n!.
Traverse from 1 to (n-r) and multiply i by den to find (n-r)!.
num/den is the final answer.
Solution 2:Optimized
Approach:
Intuition: The denominator will be lcm of den1 and den2.Then change the num1
and num2 as we changed den1 and den2 to lcm and then add the new num1 and
num2 to get the new numerator.
Approach:
Solution :
Approach:
1. Isolate the last digit, say d from the number using % operator. If d is 0 make
d’s value 1 else the digit remains as it is.
2. Use the formula ans = tmp*d+ ans to form the number.
3. Divide the original integer by 10 to discard the last digit.
4. Multiply tmp with 10.
5. Repeat step 1-4 till input integer > 0.
-> We know that prime numbers are always Odd. So a prime number (odd) cannot
be written as the sum of 2 odd prime numbers. So either of them has to be 2.
-> Now our question boils down to checking whether n-2 && n prime or not. If
both hold true return Yes or No
Approach:
-> In checking the Prime Function, we will run a loop from i =2 to sqrt(n). If n % i
is equal to 0, that means i is divisible by n, so it’s not a prime number we will
return false.
Intuition: For finding out the roots of the equation we have to find
the discriminant of the equation, which tells the nature of the roots.
Approach: