Basic maths
Basic maths
Given a number N, the task is to return the count of digits in this number.
Example:
1. After the first iteration, the value of n will be updated to 345 and the count is incremented to 1.
2. After the second iteration, the value of n will be updated to 34 and the count is incremented to
2.
3. After the third iteration, the value of n will be updated to 3 and the count is incremented to 3.
4. In the fourth iteration, the value of n will be updated to zero and the count will be incremented
to 4.
5. Then the test expression is evaluated ( n!=0 ) as false and the loop terminates with final count as
4.
Below is the implementation of the above approach:
C++Java
// JAVA Code to count number of
// digits in an integer
import java.util.*;
class GFG {
/* Driver code */
public static void main(String[] args)
{
long n = 345289467;
System.out.print("Number of digits : "
+ countDigit(n));
}
}
Output
Number of digits : 9
Time Complexity : O(log10(n)) or θ(num digits)
Auxiliary Space: O(1) or constant
Palindrome Numbers
Given an integer, write a function that returns true if the given number is palindrome, else false. For
example, 12321 is palindrome, but 1451 is not palindrome.
A simple approach to check if a number is Palindrome or not . This approach can be used when the
number of digits in the given number is less than 10^18 because if the number of digits of that number
exceeds 10^18, we can’t take that number as an integer since the range of long long int doesn’t satisfy
the given number.
To check whether the given number is palindrome or not we will just reverse the digits of the given
number and check if the reverse of that number is equal to the original number or not . If reverse of
number is equal to that number than the number will be Palindrome else it will not a Palindrome.
C++JavaPython3C#Javascript
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
// Java program to check if a number is Palindrome
Output
Yes
Time Complexity : O(log(n)) or O(Number of digits in a given number)
Let’s create a factorial program using recursive functions. Until the value is not equal to zero, the
recursive function will call itself. Factorial can be calculated using the following recursive formula.
n! = n * (n – 1)!
n == 1 if n = 0 or n = 1
Below is the implementation:
C++Java
// Java program to find factorial of given number
class Test {
// method to find factorial of given number
static int factorial(int n)
{
if (n == 0)
return 1;
// Driver method
public static void main(String[] args)
{
int num = 5;
System.out.println("Factorial of " + num
+ " is " + factorial(5));
}
}
Output
Factorial of 5 is 120
Time Complexity: O(n)
Auxiliary Space: O(n)
• Using a for loop, we will write a program for finding the factorial of a number.
• An integer variable with a value of 1 will be used in the program.
• With each iteration, the value will increase by 1 until it equals the value entered by the user.
• The factorial of the number entered by the user will be the final value in the fact variable.
Below is the implementation for the above approach:
C++Java
// C++ program for factorial of a number
// Java program to find factorial of given number
class Test {
// Driver method
public static void main(String[] args)
{
int num = 5;
System.out.println(
"Factorial of " + num
+ " is " + factorial(5));
}
}
Output
Factorial of 5 is 120
Time Complexity: O(n)
Auxiliary Space: O(1)
Mark as Read
Report An Issue
Trailing Zeros in Factorial
In a realm where numbers hold secrets, a captivating challenge awaits, which is to, Count Trailing
Zeros in Factorial !!!
Our Task: We are given a number. The task is to find the Number of Trailing Zeros in the factorial of
the number.
The Trailing Zeros are the Zeros, which appear at the end of a number(factorial in that case)
Examples :
Input: 5
Output: 1
// Factorial of 5 = 5*4*3*2*1 = 120, which has one trailing 0.
Input: 20
Output: 4
// Factorial of 20 = 20*19*18*.... 3*2*1 = 2432902008176640000 which has
4 trailing zeroes.
Input: 100
Output: 24
We have 2 approaches to solve the problem: Naive Approach & Efficient Approach
1) Naive Approach
A simple method is to first calculate the factorial of n, then count trailing 0s in the result (We can count
trailing 0s by repeatedly dividing the factorial by 10 till the remainder is not 0).
But, this method can cause overflow for slightly bigger numbers as the factorial of a number is a big
number. So, we prefer the Efficient Approach
2) Efficient Approach
The idea is to consider prime factors of a factorial n. A trailing zero is always produced by prime factors
2 and 5. Our task is done if we can count the number of 5s and 2s. Consider the following examples:
C++Java
// Java program to count
// trailing 0s in n!
import java.io.*;
class GFG {
// Function to return trailing
// 0s in factorial of n
static int findTrailingZeros(int n)
{
if (n < 0) // Negative Number Edge Case
return -1;
// Initialize result
int count = 0;
return count;
}
// Driver Code
public static void main(String[] args)
{
int n = 100;
System.out.println("Count of trailing 0s in " + n
+ "! is "
+ findTrailingZeros(n));
}
}
Output :
GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest
number that divides both of them.
It is a process of repeat subtraction, carrying the result forward each time until the result is equal to
any one number being subtracted. If the answer is greater than 1, there is a GCD (besides 1). If the
answer is 1, there is no common divisor (besides 1), and so both numbers are coprime
For Example: Suppose a=98 & b=56 a>b so put a = a-b and b remains same. So a = 98-56 = 42 & b = 56.
Since b>a, we check if b%a==0. Since answer is no we proceed further. Now b>a so b=b-a and a remain
same. So b = 56-42 = 14 & a = 42. Since a>b, we check if a%b==0. Now the answer is yes. So we print
smaller among a and b as H.C.F. i.e. 42 is 3 times of 14. So HCF is 14.
Likewise when a = 36 & b = 60, here b>a so b = 24 & a= 36 but a%b!=0. Now a>b so a = 12 & b = 24 and
b%a==0. smaller among a and b is 12 which becomes HCF of 36 and 60.
The idea is, GCD of two numbers doesn’t change if a smaller number is subtracted from a bigger
number.
C++Java
// Java program to find GCD of two numbers
class Test
{
// Recursive function to return gcd of a and b
static int gcd(int a, int b)
{
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
// Driver method
public static void main(String[] args)
{
int a = 98, b = 56;
System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b));
}
}
Output
GCD of 98 and 56 is 14
Time Complexity: O(max(a,b))
Auxiliary Space: O(max(a,b))
// Driver method
public static void main(String[] args)
{
int a = 98, b = 56;
System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b));
}
Output
GCD of 98 and 56 is 14
Time Complexity: O(log(min(a,b))|
Auxiliary Space: O(log(min(a,b))
The time complexity for the above algorithm is O(log(min(a,b))) the derivation for this is obtained from
the analysis of the worst-case scenario. What we do is we ask what are the 2 least numbers that take 1
step, those would be (1,1). If we want to increase the number of steps to 2 while keeping the numbers
as low as possible as we can take the numbers to be (1,2). Similarly, for 3 steps, the numbers would be
(2,3), 4 would be (3,5), 5 would be (5,8). So we can notice a pattern here, for the nth step the numbers
would be (fib(n), fib(n+1)). So the worst-case time complexity would be O(n) where a>= fib(n) and b>=
fib(n+1).
Now Fibonacci series is an exponentially growing series where the ratio of nth/(n-1)th term approaches
(sqrt(5)+1)/2 which is also called the golden ratio. So we can see that the time complexity of the
algorithm increases linearly as the terms grow exponentially hence the time complexity would be
log(min(a,b)).
Mark as Read
Report An Issue
LCM of Two Numbers
LCM (Least Common Multiple) of two numbers is the smallest number which can be divided by both
numbers.
A simple solution is to find all prime factors of both numbers, then find union of all factors present in
both numbers. Finally, return the product of elements in union.
An efficient solution is based on the below formula for LCM of two numbers ‘a’ and ‘b’.
LCM(a, b) = (a x b) / GCD(a, b)
We have discussed function to find GCD of two numbers. Using GCD, we can find LCM.
C++Java
// Java program to find LCM of two numbers.
class Test
{
// Recursive method to return gcd of a and b
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// Driver method
public static void main(String[] args)
{
int a = 15, b = 20;
System.out.println("LCM of " + a +
" and " + b +
" is " + lcm(a, b));
}
}
Output
LCM of 15 and 20 is 60
Time Complexity: O(log(min(a,b))
Prime numbers
• In other words, the prime number is a positive integer greater than 1 that has exactly two factors,
1 and the number itself.
• There are many prime numbers, such as 2, 3, 5, 7, 11, 13, etc.
• Keep in mind that 1 cannot be either prime or composite.
• The remaining numbers, except for 1, are classified as prime and composite numbers.
C++Java
// A school method based C++ program to
// A school method based Java program to
// check if a number is prime
import java.lang.*;
import java.util.*;
class GFG {
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// Driver code
public static void main(String[] args)
{
if (isPrime(19))
System.out.println("true");
else
System.out.println("false");
}
}
Output
true
Time Complexity: O(sqrt(n))
Auxiliary space: O(1)
Efficient approach: To check whether the number is prime or not follow the below idea:
In the previous approach given if the size of the given number is too large then its square root will
be also very large, so to deal with large size input we will deal with a few numbers such as 1, 2, 3,
and the numbers which are divisible by 2 and 3 in separate cases and for remaining numbers, we
will iterate our loop from 5 to sqrt(n) and check for each iteration whether that (iteration) or
(that iteration + 2) divides n or not. If we find any number that divides, we return false.
Below is the implementation for the above idea:
C++Java
// A school method based C++ program to
// Java program to check whether a number
import java.lang.*;
import java.util.*;
class GFG {
return true;
}
// Driver Code
public static void main(String[] args)
{
if (isPrime(11)) {
System.out.println("true");
}
else {
System.out.println("false");
}
}
}
Output :
true
Time complexity: O(sqrt(n))
Auxiliary space: O(1)
Mark as Read
Report An Issue
Prime Factors
Prime factor is the factor of the given number which is a prime number. Factors are the numbers you
multiply together to get another number. In simple words, prime factor is finding which prime numbers
multiply together to make the original number.
Example: The prime factors of 15 are 3 and 5 (because 3×5=15, and 3 and 5 are prime numbers).
1. There is only one (unique!) set of prime factors for any number.
2. In order to maintain this property of unique prime factorizations, it is necessary that the number
one, 1, be categorized as neither prime nor composite.
3. Prime factorizations can help us with divisibility, simplifying fractions, and finding common
denominators for fractions.
4. Pollard’s Rho is a prime factorization algorithm, particularly fast for a large composite
number with small prime factors.
5. Cryptography is the study of secret codes. Prime Factorization is very important to people who
try to make (or break) secret codes based on numbers.
How to print a prime factor of a number?
Naive solution:
Given a number n, write a function to print all prime factors of n. For example, if the input number is
12, then output should be “2 2 3” and if the input number is 315, then output should be “3 3 5 7”.
Following are the steps to find all prime factors:
class GFG {
// A function to print all prime factors
// of a given number n
public static void primeFactors(int n)
{
// Print the number of 2s that divide n
while (n % 2 == 0) {
System.out.print(2 + " ");
n /= 2;
}
Output:
3 3 5 7
Time Complexity: O(sqrt(n)) Auxiliary Space: O(1)
3 3 5 7
All Divisors of a Number
Input : n = 10
Output: 1 2 5 10
Input: n = 100
Output: 1 2 4 5 10 20 25 50 100
Input: n = 125
Output: 1 5 25 125
A Naive Solution would be to iterate all the numbers from 1 to n, checking if that number divides n and
printing it. Below is a program for the same:
C++Java
// Java implementation of Naive method to print all
// divisors
class Test
{
// method to print the divisors
static void printDivisors(int n)
{
for (int i=1;i<=n;i++)
if (n%i==0)
System.out.print(i+" ");
}
// Driver method
public static void main(String args[])
{
System.out.println("The divisors of 100 are: ");
printDivisors(100);;
}
}
Output:
class Test
{
// method to print the divisors
static void printDivisors(int n)
{
// Note that this loop runs till square root
for (int i=1; i<=Math.sqrt(n); i++)
{
if (n%i==0)
{
// If divisors are equal, print only one
if (n/i == i)
System.out.print(" "+ i);
// Driver method
public static void main(String args[])
{
System.out.println("The divisors of 100 are: ");
printDivisors(100);;
}
}
Output:
C++Java
import java.util.Vector;
class Test {
// method to print the divisors
static void printDivisors(int n)
{
// Vector to store half of the divisors
Vector<Integer> v = new Vector<>();
for (int i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
// Driver method
public static void main(String args[])
{
System.out.println("The divisors of 100 are: ");
printDivisors(100);
}
}
Output:
1 2 4 5 10 20 25 50 100
Time Complexity: O(sqrt(n))
Sieve of Eratosthenes
Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.
Example:
Input :n =10
Output : 2 3 5 7
Input :n = 20
Output: 2 3 5 7 11 13 17 19
The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is
smaller than 10 million or so.
Following is the algorithm to find all the prime numbers less than or equal to a given integer n by the
Eratosthene’s method:
When the algorithm terminates, all the numbers in the list that are not marked are prime.
Let us take an example when n = 50. So we need to print all prime numbers smaller than or equal to 50.
We create a list of all numbers from 2 to 50.
According to the algorithm we will mark all the numbers which are divisible by 2 and are greater than
or equal to the square of it.
Now we move to our next unmarked number 3 and mark all the numbers which are multiples of 3 and
are greater than or equal to the square of it.
We move to our next unmarked number 5 and mark all multiples of 5 and are greater than or equal to
the square of it.
We continue this process and our final table will look like below:
So the prime numbers are the unmarked ones: 2,3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47.
Implementation:
Following is the implementation of the above algorithm. In the following implementation, a boolean
array arr[] of size n is used to mark multiples of prime numbers.
C++Java
// Java program to print all primes smaller than or equal to
// n using Sieve of Eratosthenes
class SieveOfEratosthenes {
void sieveOfEratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and
// initialize all entries it as true. A value in
// prime[i] will finally be false if i is Not a
// prime, else true.
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
// Driver Code
public static void main(String args[])
{
int n = 30;
System.out.print("Following are the prime numbers ");
System.out.println("smaller than or equal to " + n);
SieveOfEratosthenes g = new SieveOfEratosthenes();
g.sieveOfEratosthenes(n);
}
}
Output
Computing Power
Given two integers x and n, write a function to compute xn. We may assume that x and n are small and
overflow doesn’t happen.
Examples :
Input :x = 2, n = 3
Output : 8
Input :x = 7, n = 2
Output : 49
Naive Approach: To solve the problem follow the below idea:
A simple solution to calculate pow(x, n) would multiply x exactly n times. We can do that by using
a simple for loop
Below is the implementation of the above approach:
C++Java
// Java program for the above approach
import java.io.*;
class Gfg {
return pow;
}
// Driver code
public static void main(String[] args)
{
int x = 2;
int n = 3;
System.out.println(power(x, n));
}
};
Output
8
Time Complexity: O(n)
Auxiliary Space: O(1)
C++Java
/* Function to calculate x raised to the power y in
* O(logn)*/
class GFG {
/* Function to calculate x raised to the power y */
static int power(int x, int y)
{
int temp;
if (y == 0)
return 1;
temp = power(x, y / 2);
if (y % 2 == 0)
return temp * temp;
else
return x * temp * temp;
}
// Driver code
public static void main(String[] args)
{
int x = 2;
int y = 3;
// Function call
System.out.printf("%d", power(x, y));
}
}
Output
8
Time Complexity: O(log n)
Auxiliary Space: O(log n), for recursive call stack
Mark as Read
Report An Issue
Modular Arithmetic
Modular arithmetic is the branch of arithmetic mathematics related with the "mod" functionality.
Basically, modular arithmetic is related with computation of "mod" of expressions. Expressions may
have digits and computational symbols of addition, subtraction, multiplication, division or any other.
Here we will discuss briefly about all modular arithmetic operations.
If a = 20, b = 6 then q = 3, r = 2, 20 = 6 x 3 + 2
Modular Addition:
Rule for modular addition is:
Modular Multiplication:
The Rule for modular multiplication is:
Modular Division:
The modular division is totally different from modular addition, subtraction and multiplication. It also
does not exist always.
Modular Inverse:
The modular inverse of a mod m exists only if a and m are relatively prime i.e. gcd(a, m) = 1. Hence, for
finding the inverse of an under modulo m, if (a x b) mod m = 1 then b is the modular inverse of a.
Example:
Modular Exponentiation:
Finding a^b mod m is the modular exponentiation. There are two approaches for this - recursive and
iterative.
Example:
a = 5, b = 2, m = 7(5 ^ 2) % 7 = 25 % 7 = 4
There is often a need to efficiently calculate the value of xn mod m. This can be done in O(logn) time
using the following recursion:
It is important that in the case of an even n, the value of xn/2 is calculated only once.
This guarantees that the time complexity of the algorithm is O(logn) because n is always halved when
it is even.
C++Java
import java.util.*;
class GFG {
//function that calculate modular exponentiation x^n mod m.
public static int modpower(int x, int n, int m) {
if (n == 0) //base case
return 1 % m;
long u = modpower(x, n / 2, m);
u = (u * u) % m;
if (n % 2 == 1) // when 'n' is odd
u = (u * x) % m;
return (int)u;
}
//driver function
public static void main(String[] args) {
System.out.println(modpower(5, 2, 7));
}
}
output:4
Time complexity: O(logn), because n is always halved when it is even.
•xm−1 mod m = 1
when m is prime and x and m are coprime. This also yields
Mark as Read
Report An Issue
Iterative Power
Given an integer x and a positive number y, write a function that computes x y under following
conditions.
a) Time complexity of the function should be O(Log y)
b) Extra Space is O(1)
Examples:
Input: x = 3, y = 5
Output: 243
Input: x = 2, y = 5
Output: 32
The recursive solutions are generally not preferred as they require space on call stack and they involve
function call overhead.
C++Java
// Iterative Java program
// to implement pow(x, n)
import java.io.*;
class GFG
{
/* Iterative Function to
calculate (x^y) in O(logy) */
static int power(int x, int y)
{
// Initialize result
int res = 1;
while (y > 0)
{
// If y is odd,
// multiply
// x with result
if ((y & 1) == 1)
res = res * x;
// Driver Code
public static void main (String[] args)
{
int x = 3;
int y = 5;
System.out.println("Power is " +
power(x, y));
}
}
Output:
Power is 243
Time Complexity: O(log y), since in loop each time the value of y decreases by half it’s current value.