Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Program to evaluate simple expressions
Next article icon

Check if a number is a power of another number

Last Updated : 12 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given two positive numbers x and y, check if y is a power of x or not.
Examples : 

Input:  x = 10, y = 1
Output: True
x^0 = 1

Input:  x = 10, y = 1000
Output: True
x^3 = 1

Input:  x = 10, y = 1001
Output: False

[Naive Approach] Repeated Multiplication Method

This approach checks whether a number y is a power of another number x by repeatedly multiplying x until it either matches or exceeds y. It starts with an initial value of 1 and keeps multiplying it by x in a loop. If the resulting value becomes equal to y, then y is a power of x; otherwise, if it exceeds y without a match, the function returns false. This method efficiently verifies powers by iteratively computing exponential values instead of using logarithms or recursion.

C++
#include <bits/stdc++.h> using namespace std;  bool isPower(int x, long int y) {     // The only power of 1 is 1 itself     if (x == 1)         return (y == 1);      // Repeatedly compute power of x     long int pow = 1;     while (pow < y)         pow *= x;      // Check if power of x becomes y     return (pow == y); }   int main() {     cout << boolalpha;       cout << isPower(10, 1) << endl;         cout << isPower(1, 20) << endl;         cout << isPower(2, 128) << endl;        cout << isPower(2, 30) << endl;         return 0; } 
C
#include <stdio.h>  int isPower(int x, long int y) {     // The only power of 1 is 1 itself     if (x == 1)         return (y == 1);      // Repeatedly compute power of x     long int pow = 1;     while (pow < y)         pow *= x;      // Check if power of x becomes y     return (pow == y); }  int main() {     printf("%d\n", isPower(10, 1));     printf("%d\n", isPower(1, 20));     printf("%d\n", isPower(2, 128));     printf("%d\n", isPower(2, 30));     return 0; } 
Java
public class Main {     public static boolean isPower(int x, long y) {         // The only power of 1 is 1 itself         if (x == 1)             return (y == 1);          // Repeatedly compute power of x         long pow = 1;         while (pow < y)             pow *= x;          // Check if power of x becomes y         return (pow == y);     }      public static void main(String[] args) {         System.out.println(isPower(10, 1));         System.out.println(isPower(1, 20));         System.out.println(isPower(2, 128));         System.out.println(isPower(2, 30));     } } 
Python
def isPower(x, y):     # The only power of 1 is 1 itself     if x == 1:         return y == 1      # Repeatedly compute power of x     pow = 1     while pow < y:         pow *= x      # Check if power of x becomes y     return pow == y  if __name__ == '__main__':     print(isPower(10, 1))     print(isPower(1, 20))     print(isPower(2, 128))     print(isPower(2, 30)) 
C#
using System;  class Program {     static bool isPower(int x, long y) {         // The only power of 1 is 1 itself         if (x == 1)             return (y == 1);          // Repeatedly compute power of x         long pow = 1;         while (pow < y)             pow *= x;          // Check if power of x becomes y         return (pow == y);     }      static void Main() {         Console.WriteLine(isPower(10, 1));         Console.WriteLine(isPower(1, 20));         Console.WriteLine(isPower(2, 128));         Console.WriteLine(isPower(2, 30));     } } 
JavaScript
function isPower(x, y) {     // The only power of 1 is 1 itself     if (x === 1)         return y === 1;      // Repeatedly compute power of x     let pow = 1;     while (pow < y)         pow *= x;      // Check if power of x becomes y     return pow === y; }  console.log(isPower(10, 1)); console.log(isPower(1, 20)); console.log(isPower(2, 128)); console.log(isPower(2, 30)); 

Output
true false true false 

Time complexity: O(Logxy)
Auxiliary space: O(1)

[Better Approach] Exponentiation and Binary Search Method

This approach efficiently checks if a number y is a power of another number x by leveraging exponential growth and binary search. It first attempts to reach or exceed y by repeatedly squaring x, which significantly reduces the number of multiplications compared to simple iteration. If the squared value matches y, the function returns true. If it overshoots y, a binary search is performed between the last two computed powers of x to find an exact match.

C++
#include <bits/stdc++.h> using namespace std;  bool isPower(int x, long int y) {     if (x == 1) return (y == 1);      long int pow = x, i = 1;      while (pow < y) {         pow *= pow;         i *= 2;     }      if (pow == y) return true;      long int low = x, high = pow;     while (low <= high) {         long int mid = low + (high - low) / 2;         long int result = powl(x, log2(mid) / log2(x));          if (result == y) return true;         if (result < y) low = mid + 1;         else high = mid - 1;     }      return false; }  int main() {     cout << boolalpha;     cout << isPower(10, 1) << endl;     cout << isPower(1, 20) << endl;     cout << isPower(2, 128) << endl;     cout << isPower(2, 30) << endl;     return 0; } 
C
#include <stdio.h> #include <math.h>  int isPower(int x, long int y) {     if (x == 1) return (y == 1);      long int pow = x;      while (pow < y) {         pow *= x;     }      return (pow == y) ? 1 : 0; }  int main() {     printf("%s\n", isPower(10, 1) ? "true" : "false");     printf("%s\n", isPower(1, 20) ? "true" : "false");     printf("%s\n", isPower(2, 128) ? "true" : "false");     printf("%s\n", isPower(2, 30) ? "true" : "false");     return 0; } 
Java
public class PowerCheck {     public static boolean isPower(int x, long y) {         if (x == 1) return (y == 1);          long pow = x;          while (pow < y) {             pow *= pow;         }          if (pow == y) return true;          long low = x, high = pow;         while (low <= high) {             long mid = low + (high - low) / 2;             long result = (long) Math.pow(x, Math.log(mid) / Math.log(x));              if (result == y) return true;             if (result < y) low = mid + 1;             else high = mid - 1;         }          return false;     }      public static void main(String[] args) {         System.out.println(isPower(10, 1));         System.out.println(isPower(1, 20));         System.out.println(isPower(2, 128));         System.out.println(isPower(2, 30));     } } 
Python
import math  def isPower(x, y):     if x == 1:         return y == 1      pow = x      while pow < y:         pow *= x      if pow == y:         return True      low, high = x, pow     while low <= high:         mid = low + (high - low) // 2         result = int(x ** (math.log(mid) / math.log(x)))          if result == y:             return True         if result < y:             low = mid + 1         else:             high = mid - 1      return False  print("true" if isPower(10, 1) else "false") print("true" if isPower(1, 20) else "false") print("true" if isPower(2, 128) else "false") print("true" if isPower(2, 30) else "false") 
C#
using System;  class Program {     public static bool IsPower(int x, long y) {         if (x == 1) return (y == 1);          long pow = x;          while (pow < y) {             pow *= pow;         }          if (pow == y) return true;          long low = x, high = pow;         while (low <= high) {             long mid = low + (high - low) / 2;             long result = (long)Math.Pow(x, Math.Log(mid) / Math.Log(x));              if (result == y) return true;             if (result < y) low = mid + 1;             else high = mid - 1;         }          return false;     }      static void Main() {         Console.WriteLine(IsPower(10, 1));         Console.WriteLine(IsPower(1, 20));         Console.WriteLine(IsPower(2, 128));         Console.WriteLine(IsPower(2, 30));     } } 
JavaScript
function isPower(x, y) {     if (x === 1) return (y === 1);      let pow = x;      while (pow < y) {         pow *= pow;     }      if (pow === y) return true;      let low = x, high = pow;     while (low <= high) {         let mid = Math.floor((low + high) / 2);         let result = Math.pow(x, Math.log(mid) / Math.log(x));          if (result === y) return true;         if (result < y) low = mid + 1;         else high = mid - 1;     }      return false; }  console.log(isPower(10, 1)); console.log(isPower(1, 20)); console.log(isPower(2, 128)); console.log(isPower(2, 30)); 

Output
false false true true 

Time Complexity – O(log log y)
Auxiliary Space – O(1)

[Expected Approach] Logarithmic Method

This approach checks if y is a power of x using logarithms. By applying the logarithm change of base formula, it computes log⁡y(x)=log⁡(y)/log⁡(x). If the result is an integer, it means that y is an exact power of x, and the function returns true. Otherwise, it returns false.

C++
#include <iostream> #include <math.h> using namespace std;  bool isPower(int x, int y) {     float res1 = log(y) / log(x);     return res1 == floor(res1); }  int main() {     cout << boolalpha;     cout << isPower(2, 128) << endl;     return 0; } 
C
#include <stdio.h> #include <math.h> #include <stdbool.h>  bool isPower(int x, int y) {     double res1 = log(y) / log(x);     return res1 == floor(res1); }  int main() {     printf("%s\n", isPower(2, 128) ? "true" : "false");     return 0; } 
Java
import java.lang.Math;  public class Main {     public static boolean isPower(int x, int y) {         double res1 = Math.log(y) / Math.log(x);         return res1 == Math.floor(res1);     }      public static void main(String[] args) {         System.out.println(isPower(2, 128));     } } 
Python
import math  def isPower(x, y):     res1 = math.log(y) / math.log(x)     return res1 == math.floor(res1)  print(isPower(2, 128)) 
C#
using System;  class Program {     static bool IsPower(int x, int y) {         double res1 = Math.Log(y) / Math.Log(x);         return res1 == Math.Floor(res1);     }      static void Main() {         Console.WriteLine(IsPower(2, 128));     } } 
JavaScript
function isPower(x, y) {     let res1 = Math.log(y) / Math.log(x);     return res1 === Math.floor(res1); }  console.log(isPower(2, 128)); 

Output
true 

Time complexity: O(1)
Auxiliary space: O(1)



Next Article
Program to evaluate simple expressions
author
kartik
Improve
Article Tags :
  • DSA
  • Mathematical
  • SAP Labs
Practice Tags :
  • SAP Labs
  • Mathematical

Similar Reads

  • Mathematical Algorithms
    The following is the list of mathematical coding problem ordered topic wise. Please refer Mathematical Algorithms (Difficulty Wise) for the difficulty wise list of problems. GCD and LCM: GCD of Two Numbers LCM of Two Numbers LCM of array GCD of array Basic and Extended Euclidean Stein’s Algorithm fo
    5 min read
  • Divisibility & Large Numbers

    • Check if a large number is divisible by 3 or not
      Given a number, the task is that we divide number by 3. The input number may be large and it may not be possible to store even if we use long long int.Examples: Input : n = 769452Output : YesInput : n = 123456758933312Output : NoInput : n = 3635883959606670431112222Output : YesSince input number may
      7 min read

    • Check if a large number is divisible by 4 or not
      Given a number, the task is to check if a number is divisible by 4 or not. The input number may be large and it may not be possible to store even if we use long long int. Examples: Input : n = 1124Output : YesInput : n = 1234567589333862Output : NoInput : n = 363588395960667043875487Output : No Usin
      12 min read

    • Check if a large number is divisible by 6 or not
      Given a number, the task is to check if a number is divisible by 6 or not. The input number may be large and it may not be possible to store even if we use long long int. Examples: Input : n = 2112Output: YesInput : n = 1124Output : NoInput : n = 363588395960667043875487Output : No[GFGTABS] C++ #inc
      7 min read

    • Check divisibility by 7
      Given a number n, the task is to check if it is divisible by 7 or not.Note: You are not allowed to use the modulo operator, floating point arithmetic is also not allowed. Examples: Input: n = 371Output: TrueExplanation: The number 371: 37 - (2×1) = 37 - 2 = 35; 3 - (2 × 5) = 3 - 10 = -7; thus, since
      6 min read

    • Check if a large number is divisible by 9 or not
      Given a large number as a string s, determine if it is divisible by 9.Note: The number might be so large that it can't be stored in standard data types like long long. Examples: Input : s = "69354"Output: YesExplanation: 69354 is divisible by 9.Input: s = "234567876799333"Output: NoExplanation: 2345
      3 min read

    • Check if a large number is divisible by 11 or not
      Given a number, the task is to check if the number is divisible by 11 or not. The input number may be large and it may not be possible to store it even if we use long long int. Examples: Input : n = 76945Output : YesInput : n = 1234567589333892Output : YesInput : n = 363588395960667043875487Output :
      7 min read

    • Divisibility by 12 for a large number
      Given a large number, the task is to check whether the number is divisible by 12 or not. Examples : Input : 12244824607284961224 Output : Yes Input : 92387493287593874594898678979792 Output : No Method 1: This is a very simple approach. if a number is divisible by 4 and 3 then the number is divisibl
      8 min read

    • Check if a large number is divisible by 13 or not
      Given a large number, the task is to check if the number is divisible by 13 or not. Examples : Input : 637Output : 637 is divisible by 13.Input : 920Output : 920 is not divisible by 13.Input : 83959092724Output : 83959092724 is divisible by 13. [Naive Approach] - Modulo Division If the given number
      14 min read

    • Check if a large number is divisibility by 15
      Given a very large number. Check its divisibility by 15. Examples: Input: "31"Output: NoInput : num = "156457463274623847239840239 402394085458848462385346236 482374823647643742374523747 264723762374620"Output: YesGiven number is divisible by 15A number is divisible by 15 if it is divisible by 5 (if
      5 min read

    • Number is divisible by 29 or not
      Given a large number n, find if the number is divisible by 29.Examples : Input : 363927598 Output : No Input : 292929002929 Output : Yes A quick solution to check if a number is divisible by 29 or not is to add 3 times of last digit to rest number and repeat this process until number comes 2 digit.
      5 min read

    GCD and LCM

    • LCM of given array elements
      In this article, we will learn how to find the LCM of given array elements. Given an array of n numbers, find the LCM of it. Example: Input : {1, 2, 8, 3}Output : 24LCM of 1, 2, 8 and 3 is 24Input : {2, 7, 3, 9, 4}Output : 252 Table of Content [Naive Approach] Iterative LCM Calculation - O(n * log(m
      15 min read

    • GCD of more than two (or array) numbers
      Given an array arr[] of non-negative numbers, the task is to find GCD of all the array elements. In a previous post we find GCD of two number. Examples: Input: arr[] = [1, 2, 3]Output: 1Input: arr[] = [2, 4, 6, 8]Output: 2 Using Recursive GCDThe GCD of three or more numbers equals the product of the
      11 min read

    • Euclidean algorithms (Basic and Extended)
      The Euclidean algorithm is a way to find the greatest common divisor of two positive integers. GCD of two numbers is the largest number that divides both of them. A simple way to find GCD is to factorize both numbers and multiply common prime factors. Examples: input: a = 12, b = 20Output: 4Explanat
      9 min read

    • Stein's Algorithm for finding GCD
      Stein's algorithm or binary GCD algorithm is an algorithm that computes the greatest common divisor of two non-negative integers. Stein’s algorithm replaces division with arithmetic shifts, comparisons, and subtraction. Examples: Input: a = 17, b = 34 Output : 17Input: a = 50, b = 49Output: 1 Algori
      14 min read

    • GCD, LCM and Distributive Property
      Given three integers x, y, z, the task is to compute the value of GCD(LCM(x,y), LCM(x,z)) where, GCD = Greatest Common Divisor, LCM = Least Common Multiple Examples: Input: x = 15, y = 20, z = 100Output: 60Explanation: The GCD of 15 and 20 is 5, and the LCM of 15 and 20 is 60, which is then multipli
      5 min read

    • Count number of pairs (A <= N, B <= N) such that gcd (A , B) is B
      Given a number n, we need to find the number of ordered pairs of a and b such gcd(a, b) is b itselfExamples : Input : n = 2Output : 3The pairs are (1, 1) (2, 2) and (2, 1) Input : n = 3Output : 5(1, 1) (2, 2) (3, 3) (2, 1) and (3, 1) [Naive Approach] Counting GCD Pairs by Divisor Propertygcd(a, b) =
      6 min read

    • Program to find GCD of floating point numbers
      The greatest common divisor (GCD) of two or more numbers, which are not all zero, is the largest positive number that divides each of the numbers. Example: Input : 0.3, 0.9Output : 0.3Explanation: The GCD of 0.3 and 0.9 is 0.3 because both numbers share 0.3 as the largest common divisor.Input : 0.48
      4 min read

    • Series with largest GCD and sum equals to n
      Given an integer n, print m increasing numbers such that the sum of m numbers is equal to n and the GCD of m numbers is maximum among all series possible. If no series is possible then print “-1”. Examples : Input : n = 24, m = 3 Output : 4 8 12 Explanation : (4, 8, 12) has gcd = 4 which is the maxi
      11 min read

    • Largest Subset with GCD 1
      Given n integers, we need to find size of the largest subset with GCD equal to 1. Input Constraint : n <= 10^5, A[i] <= 10^5 Examples: Input : A = {2, 3, 5}Output : 3Explanation: The largest subset with a GCD greater than 1 is {2, 3, 5}, and the GCD of all the elements in the subset is 3.Input
      6 min read

    • Summation of GCD of all the pairs up to n
      Given a number n, find sum of all GCDs that can be formed by selecting all the pairs from 1 to n. Examples: Input : n = 4Output : 7Explanation: Numbers from 1 to 4 are: 1, 2, 3, 4Result = gcd(1,2) + gcd(1,3) + gcd(1,4) + gcd(2,3) + gcd(2,4) + gcd(3,4) = 1 + 1 + 1 + 1 + 2 + 1 = 7Input : n = 12Output
      10 min read

    Series

    • Juggler Sequence
      Juggler Sequence is a series of integer number in which the first term starts with a positive integer number a and the remaining terms are generated from the immediate previous term using the below recurrence relation : [Tex]a_{k+1}=\begin{Bmatrix} \lfloor a_{k}^{1/2} \rfloor & for \quad even \q
      6 min read

    • Padovan Sequence
      Padovan Sequence similar to Fibonacci sequence with similar recursive structure. The recursive formula is, P(n) = P(n-2) + P(n-3) P(0) = P(1) = P(2) = 1 Fibonacci Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...... Spiral of squares with side lengths which follow the Fibonacci sequence. Padovan Sequ
      4 min read

    • Aliquot Sequence
      Given a number n, the task is to print its Aliquot Sequence. Aliquot Sequence of a number starts with itself, remaining terms of the sequence are sum of proper divisors of immediate previous term. For example, Aliquot Sequence for 10 is 10, 8, 7, 1, 0. The sequence may repeat. For example, for 6, we
      8 min read

    • Moser-de Bruijn Sequence
      Given an integer 'n', print the first 'n' terms of the Moser-de Bruijn Sequence. Moser-de Bruijn sequence is the sequence obtained by adding up the distinct powers of the number 4 (For example, 1, 4, 16, 64, etc). Examples: Input : 5 Output : 0 1 4 5 16 Input : 10 Output : 0 1 4 5 16 17 20 21 64 65
      12 min read

    • Stern-Brocot Sequence
      Stern Brocot sequence is similar to Fibonacci sequence but it is different in the way fibonacci sequence is generated . Generation of Stern Brocot sequence : 1. First and second element of the sequence is 1 and 1.2. Consider the second member of the sequence . Then, sum the considered member of the
      5 min read

    • Newman-Conway Sequence
      Newman-Conway Sequence is the one that generates the following integer sequence. 1 1 2 2 3 4 4 4 5 6 7 7... In mathematical terms, the sequence P(n) of Newman-Conway numbers is defined by the recurrence relation P(n) = P(P(n - 1)) + P(n - P(n - 1)) with seed values P(1) = 1 and P(2) = 1 Given a numb
      6 min read

    • Sylvester's sequence
      In number system, Sylvester's sequence is an integer sequence in which each member of the sequence is the product of the previous members, plus one. Given a positive integer N. The task is to print the first N member of the sequence. Since numbers can be very big, use %10^9 + 7.Examples: Input : N =
      4 min read

    • Recaman's sequence
      Given an integer n. Print first n elements of Recaman’s sequence. Recaman's Sequence starts with 0 as the first term. For each next term, calculate previous term - index (if positive and not already in sequence); otherwise, use previous term + index. Examples: Input: n = 6Output: 0, 1, 3, 6, 2, 7Exp
      8 min read

    • Sum of the sequence 2, 22, 222, .........
      Given an integer n. The task is to find the sum of the following sequence: 2, 22, 222, ......... to n terms. Examples : Input: n = 2Output: 24Explanation: For n = 2, the sum of first 2 terms are 2 + 22 = 24 Input: 3Output: 246Explanation: For n = 3, the sum of first 3 terms are 2 + 22 + 222 = 246 Us
      8 min read

    • Sum of series 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2
      Given a series 12 + 32 + 52 + 72 + . . . + (2*n - 1)2, find the sum of the series. Examples: Input: n = 4Output: 84Explanation: sum = 12 + 32 + 52 + 72 = 1 + 9 + 25 + 49 = 84 Input: n = 10 Output: 1330Explanation: sum = 12 + 32 + 52 + 72 + 92 + 112 + 132 + 152 + 172 + 192 = 1 + 9 + 24 + 49 + . . . +
      4 min read

    • Sum of the series 0.6, 0.06, 0.006, 0.0006, ...to n terms
      Given the number of terms i.e. n. Find the sum of the series 0.6, 0.06, 0.006, 0.0006, ...to n terms. Examples: Input: 2Output: 0.66Explanation: sum of the series upto 2 terms: 0.6 + 0.06 = 0.66. Input: 3Output: 0.666Explanation: sum of the series upto 3 terms: 0.6 + 0.06 + 0.006 = 0.666. Table of C
      7 min read

    • n-th term in series 2, 12, 36, 80, 150....
      Given a series 2, 12, 36, 80, 150.. Find the n-th term of the series.Examples : Input : 2 Output : 12 Input : 4 Output : 80 If we take a closer look, we can notice that series is sum of squares and cubes of natural numbers (1, 4, 9, 16, 25, .....) + (1, 8, 27, 64, 125, ....).Therefore n-th number of
      3 min read

    Number Digits

    • Minimum digits to remove to make a number Perfect Square
      Given an integer n, we need to find how many digits remove from the number to make it a perfect square. Examples : Input : 8314 Output: 81 2 Explanation: If we remove 3 and 4 number becomes 81 which is a perfect square. Input : 57 Output : -1 The idea is to generate all possible subsequences and ret
      9 min read

    • Print first k digits of 1/n where n is a positive integer
      Given a positive integer n, print first k digits after point in value of 1/n. Your program should avoid overflow and floating point arithmetic.Examples : Input: n = 3, k = 3 Output: 333 Input: n = 50, k = 4 Output: 0200 We strongly recommend to minimize the browser and try this yourself first.Let us
      5 min read

    • Check if a given number can be represented in given a no. of digits in any base
      Given a number and no. of digits to represent the number, find if the given number can be represented in given no. of digits in any base from 2 to 32.Examples : Input: 8 4 Output: Yes Possible in base 2 as 8 in base 2 is 1000 Input: 8 2 Output: Yes Possible in base 3 as 8 in base 3 is 22 Input: 8 3
      12 min read

    • Minimum Segments in Seven Segment Display
      A seven-segment display can be used to display numbers. Given an array of n natural numbers. The task is to find the number in the array that uses the minimum number of segments to display the number. If multiple numbers have a minimum number of segments, output the number having the smallest index.
      6 min read

    • Find next greater number with same set of digits
      Given a number N as string, find the smallest number that has same set of digits as N and is greater than N. If N is the greatest possible number with its set of digits, then print "Not Possible". Examples: Input: N = "218765"Output: "251678"Explanation: The next number greater than 218765 with same
      9 min read

    • Check if a number is jumbled or not
      Write a program to check if a given integer is jumbled or not. A number is said to be Jumbled if for every digit, its neighbours digit differs by max 1. Examples : Input : 6765Output : TrueAll neighbour digits differ by atmost 1. Input : 1223Output : True Input : 1235Output : False Approach: Find th
      6 min read

    • Numbers having difference with digit sum more than s
      You are given two positive integer value n and s. You have to find the total number of such integer from 1 to n such that the difference of integer and its digit sum is greater than given s.Examples : Input : n = 20, s = 5 Output :11 Explanation : Integer from 1 to 9 have diff(integer - digitSum) =
      7 min read

    • Total numbers with no repeated digits in a range
      Given a range [Tex]L, R [/Tex]find total such numbers in the given range such that they have no repeated digits. For example: 12 has no repeated digit. 22 has repeated digit. 102, 194 and 213 have no repeated digit. 212, 171 and 4004 have repeated digits. Examples: Input : 10 12 Output : 2 Explanati
      15+ min read

    • K-th digit in 'a' raised to power 'b'
      Given three numbers a, b and k, find k-th digit in ab from right side Examples: Input : a = 3, b = 3, k = 1Output : 7Explanation: 3^3 = 27 for k = 1. First digit is 7 in 27 Input : a = 5, b = 2, k = 2Output : 2Explanation: 5^2 = 25 for k = 2. First digit is 2 in 25 The approach is simple. Computes t
      5 min read

    Algebra

    • Program to add two polynomials
      Given two polynomials represented by two arrays, write a function that adds given two polynomials. Example: Input: A[] = {5, 0, 10, 6} B[] = {1, 2, 4} Output: sum[] = {6, 2, 14, 6} The first input array represents "5 + 0x^1 + 10x^2 + 6x^3" The second array represents "1 + 2x^1 + 4x^2" And Output is
      15+ min read

    • Multiply two polynomials
      Given two polynomials represented by two arrays, write a function that multiplies the given two polynomials. In this representation, each index of the array corresponds to the exponent of the variable(e.g. x), and the value at that index represents the coefficient of the term. For example, the array
      15+ min read

    • Find number of solutions of a linear equation of n variables
      Given a linear equation of n variables, find number of non-negative integer solutions of it. For example, let the given equation be "x + 2y = 5", solutions of this equation are "x = 1, y = 2", "x = 5, y = 0" and "x = 3, y = 1". It may be assumed that all coefficients in given equation are positive i
      10 min read

    • Calculate the Discriminant Value
      In algebra, Discriminant helps us deduce various properties of the roots of a polynomial or polynomial function without even computing them. Let's look at this general quadratic polynomial of degree two: ax^2+bx+c Here the discriminant of the equation is calculated using the formula: b^2-4ac Now we
      5 min read

    • Program for dot product and cross product of two vectors
      There are two vector A and B and we have to find the dot product and cross product of two vector array. Dot product is also known as scalar product and cross product also known as vector product.Dot Product - Let we have given two vector A = a1 * i + a2 * j + a3 * k and B = b1 * i + b2 * j + b3 * k.
      8 min read

    • Iterated Logarithm log*(n)
      Iterated Logarithm or Log*(n) is the number of times the logarithm function must be iteratively applied before the result is less than or equal to 1. [Tex]\log ^{*}n:=\begin{cases}0n\leq 1;\\1+\log ^{*}(\log n)n>1\end{cases} [/Tex] Applications: It is used in the analysis of algorithms (Refer Wik
      4 min read

    • Program to Find Correlation Coefficient
      The correlation coefficient is a statistical measure that helps determine the strength and direction of the relationship between two variables. It quantifies how changes in one variable correspond to changes in another. This coefficient, sometimes referred to as the cross-correlation coefficient, al
      9 min read

    • Program for Muller Method
      Given a function f(x) on floating number x and three initial distinct guesses for root of the function, find the root of function. Here, f(x) can be an algebraic or transcendental function.Examples: Input : A function f(x) = x[Tex]^3[/Tex] + 2x[Tex]^2[/Tex] + 10x - 20 and three initial guesses - 0,
      13 min read

    • Number of non-negative integral solutions of a + b + c = n
      Given a number n, find the number of ways in which we can add 3 non-negative integers so that their sum is n.Examples : Input : n = 1 Output : 3 There are three ways to get sum 1. (1, 0, 0), (0, 1, 0) and (0, 0, 1) Input : n = 2 Output : 6 There are six ways to get sum 2. (2, 0, 0), (0, 2, 0), (0, 0
      7 min read

    • Generate Pythagorean Triplets
      Given a positive integer limit, your task is to find all possible Pythagorean Triplet (a, b, c), such that a <= b <= c <= limit. Note: A Pythagorean triplet is a set of three positive integers a, b, and c such that a2 + b2 = c2. Input: limit = 20Output: 3 4 5 5 12 13 6 8 10 8 15 17 9 12 15
      15 min read

    Number System

    • Exponential notation of a decimal number
      Given a positive decimal number, find the simple exponential notation (x = a·10^b) of the given number. Examples: Input : 100.0 Output : 1E2 Explanation: The exponential notation of 100.0 is 1E2. Input :19 Output :1.9E1 Explanation: The exponential notation of 16 is 1.6E1. Approach: The simplest way
      5 min read

    • Check if a number is power of k using base changing method
      This program checks whether a number n can be expressed as power of k and if yes, then to what power should k be raised to make it n. Following example will clarify : Examples: Input : n = 16, k = 2 Output : yes : 4 Explanation : Answer is yes because 16 can be expressed as power of 2. Input : n = 2
      9 min read

    • Program to convert a binary number to hexadecimal number
      Given a Binary Number, the task is to convert the given binary number to its equivalent hexadecimal number. The input could be very large and may not fit even into an unsigned long long int. Examples:  Input: 110001110Output: 18EInput: 1111001010010100001.010110110011011Output: 794A1.5B36 794A1D9B A
      13 min read

    • Program for decimal to hexadecimal conversion
      Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent hexadecimal number. i.e. convert the number with base value 10 to base value 16. Hexadecimal numbers use 16 values to represent a number. Numbers from 0-9 are expressed by digits 0-9 an
      8 min read

    • Converting a Real Number (between 0 and 1) to Binary String
      Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print" ERROR:' Examples: Input : (0.625)10 Output : (0.101)2 Input : (0.72)10 Output : ERROR Solution:
      12 min read

    • Convert from any base to decimal and vice versa
      Given a number and its base, convert it to decimal. The base of number can be anything such that all digits can be represented using 0 to 9 and A to Z. The value of A is 10, the value of B is 11 and so on. Write a function to convert the number to decimal. Examples: Input number is given as string a
      15+ min read

    • Decimal to binary conversion without using arithmetic operators
      Find the binary equivalent of the given non-negative number n without using arithmetic operators. Examples: Input : n = 10Output : 1010 Input : n = 38Output : 100110 Note that + in below algorithm/program is used for concatenation purpose. Algorithm: decToBin(n) if n == 0 return "0" Declare bin = ""
      8 min read

    Prime Numbers & Primality Tests

    • Prime Numbers | Meaning | List 1 to 100 | Examples
      Prime numbers are those natural numbers that are divisible by only 1 and the number itself. Numbers that have more than two divisors are called composite numbers All primes are odd, except for 2. Here, we will discuss prime numbers, the list of prime numbers from 1 to 100, various methods to find pr
      13 min read

    • Left-Truncatable Prime
      A Left-truncatable prime is a prime which in a given base (say 10) does not contain 0 and which remains prime when the leading ("left") digit is successively removed. For example, 317 is left-truncatable prime since 317, 17 and 7 are all prime. There are total 4260 left-truncatable primes.The task i
      13 min read

    • Program to Find All Mersenne Primes till N
      Mersenne Prime is a prime number that is one less than a power of two. In other words, any prime is Mersenne Prime if it is of the form 2k-1 where k is an integer greater than or equal to 2. First few Mersenne Primes are 3, 7, 31 and 127.The task is print all Mersenne Primes smaller than an input po
      9 min read

    • Super Prime
      Given a positive integer n and the task is to print all the Super-Primes less than or equal to n. Super-prime numbers (also known as higher order primes) are the subsequence of prime number sequence that occupy prime-numbered positions within the sequence of all prime numbers. The first few super pr
      6 min read

    • Hardy-Ramanujan Theorem
      Hardy Ramanujam theorem states that the number of prime factors of n will approximately be log(log(n)) for most natural numbers nExamples : 5192 has 2 distinct prime factors and log(log(5192)) = 2.1615 51242183 has 3 distinct prime facts and log(log(51242183)) = 2.8765 As the statement quotes, it is
      6 min read

    • Rosser's Theorem
      In mathematics, Rosser's Theorem states that the nth prime number is greater than the product of n and natural logarithm of n for all n greater than 1. Mathematically, For n >= 1, if pn is the nth prime number, then pn > n * (ln n) Illustrative Examples: For n = 1, nth prime number = 2 2 >
      15 min read

    • Fermat's little theorem
      Fermat's little theorem states that if p is a prime number, then for any integer a, the number a p - a is an integer multiple of p. Here p is a prime number ap ≡ a (mod p). Special Case: If a is not divisible by p, Fermat's little theorem is equivalent to the statement that a p-1-1 is an integer mul
      8 min read

    • Introduction to Primality Test and School Method
      Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of the first few prime numbers are {2, 3, 5, ...}Examples : Input: n = 11Output: true Input: n = 15Output: false Input: n = 1Outpu
      10 min read

    • Vantieghems Theorem for Primality Test
      Vantieghems Theorem is a necessary and sufficient condition for a number to be prime. It states that for a natural number n to be prime, the product of [Tex]2^i - 1 [/Tex]where [Tex]0 < i < n [/Tex], is congruent to [Tex]n~(mod~(2^n - 1)) [/Tex]. In other words, a number n is prime if and only
      4 min read

    • AKS Primality Test
      There are several primality test available to check whether the number is prime or not like Fermat's Theorem, Miller-Rabin Primality test and alot more. But problem with all of them is that they all are probabilistic in nature. So, here comes one another method i.e AKS primality test (Agrawal–Kayal–
      11 min read

    • Lucas Primality Test
      A number p greater than one is prime if and only if the only divisors of p are 1 and p. First few prime numbers are 2, 3, 5, 7, 11, 13, ...The Lucas test is a primality test for a natural number n, it can test primality of any kind of number.It follows from Fermat’s Little Theorem: If p is prime and
      12 min read

    Prime Factorization & Divisors

    • Print all prime factors of a given number
      Given a number n, the task is to find all prime factors of n. Examples: Input: n = 24Output: 2 2 2 3Explanation: The prime factorization of 24 is 23×3. Input: n = 13195Output: 5 7 13 29Explanation: The prime factorization of 13195 is 5×7×13×29. Approach: Every composite number has at least one prime
      6 min read

    • Smith Number
      Given a number n, the task is to find out whether this number is smith or not. A Smith Number is a composite number whose sum of digits is equal to the sum of digits in its prime factorization. Examples: Input : n = 4Output : YesPrime factorization = 2, 2 and 2 + 2 = 4Therefore, 4 is a smith numberI
      15 min read

    • Sphenic Number
      A Sphenic Number is a positive integer n which is a product of exactly three distinct primes. The first few sphenic numbers are 30, 42, 66, 70, 78, 102, 105, 110, 114, ... Given a number n, determine whether it is a Sphenic Number or not. Examples: Input: 30Output : YesExplanation: 30 is the smalles
      8 min read

    • Hoax Number
      Given a number 'n', check whether it is a hoax number or not. A Hoax Number is defined as a composite number, whose sum of digits is equal to the sum of digits of its distinct prime factors. It may be noted here that, 1 is not considered a prime number, hence it is not included in the sum of digits
      13 min read

    • k-th prime factor of a given number
      Given two numbers n and k, print k-th prime factor among all prime factors of n. For example, if the input number is 15 and k is 2, then output should be "5". And if the k is 3, then output should be "-1" (there are less than k prime factors). Examples: Input : n = 225, k = 2 Output : 3 Prime factor
      15+ min read

    • Pollard's Rho Algorithm for Prime Factorization
      Given a positive integer n, and that it is composite, find a divisor of it.Example: Input: n = 12;Output: 2 [OR 3 OR 4]Input: n = 187;Output: 11 [OR 17]Brute approach: Test all integers less than n until a divisor is found. Improvisation: Test all integers less than ?nA large enough number will stil
      14 min read

    • Finding power of prime number p in n!
      Given a number 'n' and a prime number 'p'. We need to find out the power of 'p' in the prime factorization of n!Examples: Input : n = 4, p = 2 Output : 3 Power of 2 in the prime factorization of 2 in 4! = 24 is 3 Input : n = 24, p = 2 Output : 22 Naive approach The naive approach is to find the powe
      8 min read

    • Find all factors of a Natural Number
      Given a natural number n, print all distinct divisors of it. Examples: Input: n = 10 Output: 1 2 5 10Explanation: 1, 2, 5 and 10 are the factors of 10. Input: n = 100Output: 1 2 4 5 10 20 25 50 100Explanation: 1, 2, 4, 5, 10, 20, 25, 50 and 100 are factors of 100. Input: n = 125Output: 1 5 25 125 No
      7 min read

    • Find numbers with n-divisors in a given range
      Given three integers a, b, n .Your task is to print number of numbers between a and b including them also which have n-divisors. A number is called n-divisor if it has total n divisors including 1 and itself. Examples: Input : a = 1, b = 7, n = 2 Output : 4 There are four numbers with 2 divisors in
      14 min read

    Modular Arithmetic

    • Modular Exponentiation (Power in Modular Arithmetic)
      Modular Exponentiation is the process of computing: xy (mod  p). where x, y, and p are integers. It efficiently calculates the remainder when xy is divided by p or (xy) % p, even for very large y. Examples : Input: x = 2, y = 3, p = 5Output: 3Explanation: 2^3 % 5 = 8 % 5 = 3.Input: x = 2, y = 5, p =
      8 min read

    • Modular multiplicative inverse
      Given two integers A and M, find the modular multiplicative inverse of A under modulo M.The modular multiplicative inverse is an integer X such that: A * X ≡ 1 (mod M) Note: The value of X should be in the range {1, 2, ... M-1}, i.e., in the range of integer modulo M. ( Note that X cannot be 0 as A*
      15+ min read

    • Modular Division
      Modular division is the process of dividing one number by another in modular arithmetic. In modular arithmetic, division is defined differently from regular arithmetic because there is no direct "division" operation. Instead, modular division involves multiplying by the modular multiplicative invers
      10 min read

    • Euler's criterion (Check if square root under modulo p exists)
      Given a number 'n' and a prime p, find if square root of n under modulo p exists or not. A number x is square root of n under modulo p if (x*x)%p = n%p. Examples : Input: n = 2, p = 5 Output: false There doesn't exist a number x such that (x*x)%5 is 2 Input: n = 2, p = 7 Output: true There exists a
      11 min read

    • Find sum of modulo K of first N natural number
      Given two integer N ans K, the task is to find sum of modulo K of first N natural numbers i.e 1%K + 2%K + ..... + N%K. Examples : Input : N = 10 and K = 2. Output : 5 Sum = 1%2 + 2%2 + 3%2 + 4%2 + 5%2 + 6%2 + 7%2 + 8%2 + 9%2 + 10%2 = 1 + 0 + 1 + 0 + 1 + 0 + 1 + 0 + 1 + 0 = 5.Recommended PracticeReve
      9 min read

    • How to compute mod of a big number?
      Given a big number 'num' represented as string and an integer x, find value of "num % a" or "num mod a". Output is expected as an integer. Examples : Input: num = "12316767678678", a = 10 Output: num (mod a) ? 8 The idea is to process all digits one by one and use the property that xy (mod a) ? ((x
      4 min read

    • Exponential Squaring (Fast Modulo Multiplication)
      Given two numbers base and exp, we need to compute baseexp under Modulo 10^9+7 Examples: Input : base = 2, exp = 2Output : 4Input : base = 5, exp = 100000Output : 754573817In competitions, for calculating large powers of a number we are given a modulus value(a large prime number) because as the valu
      12 min read

    • Trick for modular division ( (x1 * x2 .... xn) / b ) mod (m)
      Given integers x1, x2, x3......xn, b, and m, we are supposed to find the result of ((x1*x2....xn)/b)mod(m). Example 1: Suppose that we are required to find (55C5)%(1000000007) i.e ((55*54*53*52*51)/120)%1000000007 Naive Method : Simply calculate the product (55*54*53*52*51)= say x,Divide x by 120 an
      9 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences