0% found this document useful (0 votes)
20 views45 pages

Numbers Basicsss

Uploaded by

Atharwa Kanungo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views45 pages

Numbers Basicsss

Uploaded by

Atharwa Kanungo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Check if a number is Palindrome or Not

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.

Let’s understand the procedure to reverse a number.

 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.

Space Complexity: O(1)

Find all Palindrome Numbers in a given


range
Intuition: We run a for loop, and check for every number individually, if it is
palindrome then we will print it.

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:

 Make a result variable.


 Take the last digit of the element.
 Now multiple variable by 10 and add the last digit.
 Repeat till element>0.

Check if a number is prime or not


Running the for loop till the square root of the number

A prime number is a natural number that is only divisible by 1 and by itself.


Examples 1 2 3 5 7 11 13 17 19 …
Using a for loop for checking if the number is divisible by a number from 2 to its
square root.

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.

Prime Numbers in a given range


Approach: Prime numbers b/w a and b can be found out by iterating through
every number from a and b and checking for the number whether it is a prime
number or not.
Check if a number is Armstrong Number or
not
Approach:
Let us check one 3-digit Armstrong Number

n=153

sum=0

No. of digits = 3 so we need to cube every digit.

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.

This means it is an Armstrong Number.

Check whether a number is Perfect


Number or not
Intuition:

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.

Check whether a given number is even or


odd
Solution1: Using division

Intuition: If we can prove that the given number is divisible by 2 then it will be
even, otherwise it will be odd.

Approach:

 Find the remainder of the number.


 If it is 0 then the number is even otherwise it is odd.
Solution2: Using the bitwise operator

Intuition: As we know that bitwise operations are generally faster than normal
operations so we should prefer it over normal operations.

Even Number: The last bit of even number is always 0.

Odd Number: Last bit of the odd number is always 1.

If we can get the last bit of any number then we can say that it is even or odd.

Approach:

 Take AND of n with 1.


 If it is 0 then print even otherwise odd.
Check whether a number is positive or
negative
Solution1: Using conditions

Intuition: As we know if a number is greater than 0 then it is positive otherwise it


is negative.

Hence we can compare our number with 0 to get the answer.

Approach:

 Compare n with zero.


 If it is greater than 0, it is positive.
 If it is lesser than 0, it is negative.
Solution 2: Using Bitwise operators

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 = 0000 0000 0000 0000 0000 0000 0000 0101 = 5

b = 1111 1111 1111 1111 1111 1111 1111 1010 = -6

a>>31

a= 0000 0000 0000 0000 0000 0000 0000 0000 = 0

b>>31

b= 1111 1111 1111 1111 1111 1111 1111 1111 = -1


Approach:

 Right Shift n by 31.


 If we get 0 then n is positive.
 If we get -1 then n is negative.

Sum of first N Natural Numbers


Solution1: Using Loop

Intuition: We can simply add numbers one by one from 1 to N.

For eg. if N = 5, we can add 1+2+3+4+5=15.

We can use a for loop or while loop to achieve the goal.

Approach:

 Take a variable sum and initialize it as 0.


 Take a for loop and run from 1 to N.
 Save the result in sum.
2. Functional way

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,

a=2 , d=4, n=5

So run the loop 5 times.


Program to find Sum of GP Series
Greatest of two numbers
Greatest of three numbers
Check if given year is a leap year or not
Intuition: A year is a leap year only if it satisfies the following condition.

 The year is divisible by 400


 The year is divisible by 4 but not by 100

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.

Reverse digits of a number


Intuition: Let’s say we have a three-digit number. Observe that we need to make
the ten’s digit is the hundred’s digit and vice versa. Can we implement this by
extracting the individual digits?
Approach:

 Initialize our result as 0. We then start extracting digits one by one


 For every digit extracted we store it in our result as res=res*10+d
 Divide the number by 10 and repeat the process. Here’s a quick
demonstration of the same

Maximum and Minimum Digit in a


Number
uition: The first thing that comes to our mind is to go through individual digits of
the number and update the maximum and minimum digits that we come across.
Notice, how this problem resembles the pattern of the sum of digits, reversing of
digits in a number. All these questions come under the same format of extracting
the digits, doing some calculations, and coming up with an answer.
Approach :

 Get every digit of the number using the modulus operator


 Update the max and min digit on the go and repeat the process until the
number is not zero
 Here’s a quick demonstration of the same

Print Fibonacci Series up to Nth term


Solution 1: Naive approach

Intuition: As we know fib(i) = fib(i-1) + fib(i-2).Simply iterate and go on


calculating the ith term in the series.

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).

Solution 2: Space optimized

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:

Fibonacci(N) = Fibonacci(N-1) + Fibonacci(N-2)


Results from both the function calls would be summed and returned to the main function call.

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.

Factorial of a Number : Iterative and


Recursive
olution 1: Iterative

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

Intuition: Simply multiply n for k times.

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.

Solution 2: Binary exponentiation.

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.

If k is odd (nk) can be written as n.(n)k-1, so now (k-1) is even.

Approach:

 Maintain a variable ans to store the final answer.


 If k is even,square n and divide k by 2.as nk can be written as (n2)k/2 i.e (n*n)k/2.
 If k is odd,multiply ans with n and reduce k by 1,as nk can be written as n*(n)k-1.
 Print the ans.
Factors of a Given Number
Solution1: Brute force

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:

 Use a for loop from 1 to n.


 If n is divisible by any element of the loop then print it.
 Otherwise skip it.

olution2: Optimised 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:

 Run a for loop from 1 to SquareRoot of n.


 If n is divisible by any number i then the quotient of n/i is also divisible by n, print both i and
n/i.
 Take care of the edge case when n/i=i, print only i one time, to remove duplicates.
Print all Prime Factors of the given number
Solution 1: Brute Force Approach

Intuition:

 Let’s take a number x = 2 .


 We will start with 2 and go on till N-1 and will check whether we can get
the remainder as 0 or not when we divide this x by N . If we get the
remainder as 0 , that means the x is a factor of N.
 Now, we will divide N by x as much as we can, and will keep changing N to
N/x. It’s the exact approach that was taught to us in junior classes.

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.

Solution 2: Square Root Method

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.

Q) How do we know that N is now reduced to the Prime number ???

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 ,

then N = Q*R , P*P = N where Q , R = natural number and P = real number .

There can be 3 cases now :

1. P > Q -> R < P


2. P = Q -> R = Q
3. P < Q -> R > P

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.

Check if a number is a Strong Number or


not
Approach :

 Declare a variable to store the sum of factorials.Initialize it to 0.


 Extract the individual digits of the given number and calculate the digits’s
factorial.
 Add the computed factorial to the sum variable.
 Once all the digits have been extracted and their factorial has been added in
the sum, compare the original number with sum.
If found equal print “YES” otherwise “NO”.

Check if a number is Automorphic Number


Problem Statement: Given a number, check if it is automorphic or not. A number
is called an Automorphic number if and only if its square ends in the same digits as
the number itself.

First Store the square of the given number in an integer.

Run a loop until the number becomes 0.

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:

 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.
Solution 2: Using Euclidean’s theorem.

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:

 Recursively call gcd(b,a%b) function till the base condition is hit.


 b==0 is the base condition.When base condition is hit return a,as gcd(a,0) is
equal to a.
Find LCM of two numbers
Solution 1:Brute force

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.

Solution 2: Using Euclidean’s theorem.

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:

 First find gcd using euclidean’s algorithm,

 Recursively call gcd(b,a%b) function till the base condition is hit.


 b==0 is the base condition.When base condition is hit return a,as gcd(a,0) is
equal to a.
 Once we get gcd,we can find lcm using formula lcm = (a*b)/gcd.

Check if the given number is Harshad(Or


Niven) Number
Solution 1:

Intuition: If the sum of digits is divisible by the number then it is called Harshad
number.
Approach:

 Maintain a variable sum to store sum of digits of the number.


 Now check if n is divisible by sum or not.
 If it is divisible print yes,else print no.

Solution 2: Using string

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:

 Convert the intger to string.


 Traverse through the string and calculate the sum of all the digits.
 Now check if the number is divisible by the sum of digits or not.
 If the number is divisible, print yes, else print no.
Check if the number is an abundant
number or not
Definition: If the sum of divisors of a number is greater than the number then
it is called abundant number.

Solution 1:Naive approach

Intuition: Traverse from 1 to n and find the divisor of the number.

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”.

Sum Of Digits of A Number


Intuition: We can see that we somehow need to extract the individual digits of a
number and sum them up. Is there any operator that we know of that can be used to
extract digits from a number?

Modulus operation(%) : 10%3 = 1(Modulus operation gives us the remainder


when we divide a fraction)

Divisor operation(/) : 10/3 = 3(Divisor operation gives us the quotient when we


divide a fraction)

Note: Did you notice we get the last digit of a number when we perform a modulus
operation with a value of 10
Approach:

 Get the last digit of the number


 Add the last digit to a sum variable
 Divide the number by 10 and repeat the process until the number is not zero

Find the sum of numbers in the given range


olution 1:Naive approach

Intuition: Simply add numbers from l to r.

Approach:

 Maintain a sum variable to store the sum of elements from l to r.


 Traverse from l to r and add i to the sum.
 Once the traversal is complete print the sum.

Permutations in which N people can occupy


R seats
ntuition: The permutation in which n people can occupy r seats is n!/(n-r)!.

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

Intuition: n!/(n-r)! can also be written as n*(n-1)*(n-2)….(n-r+1).Using this we


can calculate n!/(n-r)! in O(n) time complexity.

Approach:

 Maintain a variable ans to store answer.


 Now run a for loop from n to (n-r+1) and multiply i to ans.
 Print ans.
Program to Add two fractions
Solution:

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:

 We will maintain num3 and den3 to store answers.


 First find gcd of den1 and den2 using euclidean’s algorithm.Once we get the
gcd we can easily find lcm.lcm(den1,den2) is (den1*den2)/gcd(den1,den2).
 Now we will have to change num1 and num2 to num1*(den3/den1) and
num2*(den3/den2),since we changed den1 and den2 to lcm.
 Now add num1 and num2 and store it in the num3.
 Now we have num3 and den3.The answer should be num3/den3,but before
printing the answer we should convert it into the simplest form.
 To convert it into the simplest form,divide numerator and denominator both
by gcd of numerator and denominator.
 Print num3 / den3.

Replace all the 0’s with 1 in a given integer

Solution :

Approach:

Maintain a variable and, store the modified integer. Initialize it to 0. Another


variable tmp is used which is initialized to 1.
Procedure:-

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.

Express given number as Sum of Two


Prime Numbers
Intuition:

-> 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:

-> We will create 2 functions :

1. To check Prime number


2. To check whether both N and N-2 are prime or not

-> 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.

-> Same above can be done for n-2.


Program to Find Roots of a quadratic
equation
Solution: Using Discriminant and formula

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.

Then use the formula of finding the roots.

Approach:

 Find discriminant of the equation.


 Discriminant(D) = b^2 – 4a*c
 If the discriminant is greater than 0, the roots are real and different.
 If the discriminant is equal to 0, the roots are real and equal.
 If the discriminant is less than 0, the roots are complex and different.

You might also like