Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Convert from any base to decimal and vice versa
Next article icon

Converting a Real Number (between 0 and 1) to Binary String

Last Updated : 13 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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: First, let's start off by asking ourselves what a non-integer number in binary looks like. By analogy to a decimal number, the binary number 0 .1012 would look like: 
0. 1012 = 1 * 1/21 + 0 *1/22 + 1 * 1/23 . 

Method 1: Multiply the decimal part by 2

To print the decimal part, we can multiply by 2 and check if 2*n is greater than or equal to 1. This is essentially "shifting" the fractional sum. That is: 

r = 210 * n;   = 210 * 0.1012;   = 1 * 1/20 + 0 *1/21 + 1 * 1/22;   = 1.012;


If r >= 1, then we know that n had a 1 right after the decimal point. By doing this continuously, we can check every digit. 

C++
// C++ program to binary real number to string #include <iostream> #include<string> using namespace std;  // Function to convert Binary real // number to String string toBinary(double n) {     // Check if the number is Between 0 to 1 or Not     if (n >= 1 || n <= 0)         return "ERROR";      string answer;     double frac = 0.5;     answer.append(".");      // Setting a limit on length: 32 characters.              while (n > 0)     {                  //Setting a limit on length: 32 characters              if (answer.length() >= 32)                 return "ERROR";              // Multiply n by 2 to check it 1 or 0             double b = n * 2;             if (b >= 1)             {                 answer.append("1");                 n = b - 1;             }             else             {                 answer.append("0");                 n = b;             }         }         return answer; }  // Driver code int main() {     // Input value      double n = 0.625;           string result = toBinary(n);     cout<<"(0"<< result <<") in base 2"<<endl;      double m = 0.72;     result= toBinary(m);     cout<<"("<<result<<")"<<endl;  }  // This code is contributed by Himanshu Batra 
Java
// Java program to Binary real number to String. import java.lang.*; import java.io.*; import java.util.*;  // Class Representation of Binary real number // to String class BinaryToString {     // Main function to convert Binary real number     // to String     static String printBinary(double num)     {         // Check Number is Between 0 to 1 or Not         if (num >= 1 || num <= 0)             return "ERROR";          StringBuilder binary = new StringBuilder();         binary.append(".");          while (num > 0)         {             /* Setting a limit on length: 32 characters,                If the number cannot be represented                accurately in binary with at most 32                character  */             if (binary.length() >= 32)                 return "ERROR";              // Multiply by 2 in num to check it 1 or 0             double r = num * 2;             if (r >= 1)             {                 binary.append(1);                 num = r - 1;             }             else             {                 binary.append(0);                 num = r;             }         }         return binary.toString();     }      // Driver Code     public static void main(String[] args)     {         double num1 = 0.625; // Input value in Decimal         String output = printBinary(num1);         System.out.println("(0" + output + ")  in base 2");          double num2 = 0.72;         output = printBinary(num2);         System.out.println("(" + output + ") ");     } } 
Python3
# Python3 program to binary real number to string  # Function to convert Binary real # number to String def toBinary(n):      # Check if the number is Between 0 to 1 or Not     if(n >= 1 or n <= 0):         return "ERROR"      answer = ""     frac = 0.5     answer = answer + "."      # Setting a limit on length: 32 characters.     while(n > 0):          # Setting a limit on length: 32 characters         if(len(answer) >= 32):             return "ERROR"          # Multiply n by 2 to check it 1 or 0         b = n * 2         if (b >= 1):              answer = answer + "1"             n = b - 1          else:             answer = answer + "0"             n = b      return answer  # Driver code if __name__=='__main__':     n = 0.625     result = toBinary(n)     print("(0", result, ") in base 2")     m = 0.72     result = toBinary(m)     print("(", result, ")")  # This code is contributed by # Sanjit_Prasad 
C#
// C# program to Binary real number to String.   using System; using System.Text;  // Class Representation of Binary real number  // to String  class BinaryToString  {      // Main function to convert Binary real number      // to String      static String printBinary(double num)      {          // Check Number is Between 0 to 1 or Not          if (num >= 1 || num <= 0)              return "ERROR";           StringBuilder binary = new StringBuilder();          binary.Append(".");           while (num > 0)          {              /* Setting a limit on length: 32 characters,              If the number cannot be represented              accurately in binary with at most 32              character */             if (binary.Length >= 32)                  return "ERROR";               // Multiply by 2 in num to check it 1 or 0              double r = num * 2;              if (r >= 1)              {                  binary.Append(1);                  num = r - 1;              }              else             {                  binary.Append(0);                  num = r;              }          }          return binary.ToString();      }       // Driver Code      public static void Main()      {          double num1 = 0.625; // Input value in Decimal          String output = printBinary(num1);          Console.WriteLine("(0 " + output + ") in base 2");           double num2 = 0.72;          output = printBinary(num2);      Console.WriteLine("(" + output + ") ");      }  }  
PHP
<?php // PHP program to binary real number // to string  // Function to convert Binary real // number to String function toBinary($n) {     // Check if the number is Between     // 0 to 1 or Not     if ($n >= 1 || $n <= 0)         return "ERROR";      $answer = "";     $frac = 0.5;     $answer .= ".";      // Setting a limit on length: 32 characters.              while ($n > 0)     {                  //Setting a limit on length: 32 characters          if (strlen($answer) >= 32)                 return "ERROR";              // Multiply n by 2 to check it 1 or 0             $b = $n * 2;             if ($b >= 1)             {                 $answer .= "1";                 $n = $b - 1;             }             else             {                 $answer .= "0";                 $n = $b;             }         }         return $answer; }  // Driver code  // Input value  $n = 0.625;   $result = toBinary($n); echo "(0" . $result . ") in base 2\n";  $m = 0.72; $result= toBinary($m); echo "(" . $result . ")";      // This code is contributed by mits ?> 
JavaScript
<script>  // JavaScript program to binary real number to string  // Function to convert Binary real // number to String function toBinary(n){      // Check if the number is Between 0 to 1 or Not     if(n >= 1 || n <= 0)         return "ERROR"      let answer = ""     let frac = 0.5     answer = answer + "."      // Setting a limit on length: 32 characters.     while(n > 0){          // Setting a limit on length: 32 characters         if(answer.length >= 32){             return "ERROR"         }          // Multiply n by 2 to check it 1 or 0         b = n * 2         if (b >= 1){              answer = answer + "1"             n = b - 1         }          else{             answer = answer + "0"             n = b         }     }      return answer }  // Driver code  let n = 0.625 let result = toBinary(n) document.write(`(0 ${result}) in base 2`,"</br>") let m = 0.72 result = toBinary(m) document.write(`(${result})`,"</br>")  // This code is contributed by Shinjanpatra  </script> 

Output: 

(0.101)  in base 2 (ERROR) 

Method 2

Alternatively, rather than multiplying the number by two and comparing it to 1, we can compare the number to . 5, then . 25, and so on. The code below demonstrates this approach.  

C++
// C++ program to Binary real number to String. #include <iostream> #include<string> using namespace std;  // Function to convert Binary real // number to String string toBinary(double n) {     // Check if the number is Between 0 to 1 or Not     if (n >= 1 || n <= 0)         return "ERROR";      string answer;     double frac = 0.5;     answer.append(".");      // Setting a limit on length: 32 characters.              while (n > 0)     {         // 32 char max         if (answer.length() >= 32)             return "ERROR";     // compare the number to .5         if (n >= frac)         {             answer.append("1");             n = n- frac;         }         else         {             answer.append("0");         }                  frac /= 2;     }     return answer; }  // Driver code int main() {     // Input value      double n = 0.625;          string result = toBinary(n);     cout<<"(0"<< result <<") in base 2"<<endl;      double m = 0.72;     result= toBinary(m);     cout<<"("<<result<<")"<<endl;  } 
Java
// Java program to Binary real number to String. import java.lang.*; import java.io.*; import java.util.*;  // Class representation of Binary real number // to String class BinaryToString {     // Main function to convert Binary real     // number to String     static String printBinary(double num)     {         // Check Number is Between 0 to 1 or Not         if (num >= 1 || num <= 0)             return "ERROR";          StringBuilder binary = new StringBuilder();         double frac = 0.5;         binary.append(".");          while (num > 0)         {             /* Setting a limit on length: 32 characters,                If the number cannot be represented                accurately in binary with at most 32                characters  */             if (binary.length() >= 32)                 return "ERROR";              // It compare the number to . 5.             if (num >= frac)             {                 binary.append(1);                 num -= frac;             }             else                             binary.append(0);              // Now it become 0.25             frac /= 2;         }         return binary.toString();     }      // Driver Code     public static void main(String[] args)     {         double num1 = 0.625; // Input value in Decimal         String output = printBinary(num1);         System.out.println("(0" + output + ")  in base 2");          double num2 = 0.72;         output = printBinary(num2);         System.out.println("(" + output + ") ");     } } 
Python3
# Python3 program to Binary real number to String.  # Function to convert Binary real # number to String def toBinary(n):      # Check if the number is Between      # 0 to 1 or Not     if (n >= 1 or n <= 0):         return "ERROR";      frac = 0.5;     answer = ".";      # Setting a limit on length: 32 characters.          while (n > 0):                  # 32 char max         if (len(answer) >= 32):             return "ERROR";                      # compare the number to .5         if (n >= frac):             answer += "1";             n = n - frac;         else:             answer += "0";                  frac = (frac / 2);          return answer;  # Driver code  # Input value  n = 0.625;  result = toBinary(n); print("( 0", result, ") in base 2");  m = 0.72; result = toBinary(m); print("(", result, ")");   # This code is contributed  # by mits 
C#
// C# program to Binary real number to String.  using System;  // Class representation of Binary  // real number to String  class BinaryToString  {      // Main function to convert Binary     // real number to String      static string printBinary(double num)      {          // Check Number is Between          // 0 to 1 or Not          if (num >= 1 || num <= 0)              return "ERROR";           string binary = "";          double frac = 0.5;          binary += ".";           while (num > 0)          {              /* Setting a limit on length: 32 characters,              If the number cannot be represented              accurately in binary with at most 32              characters */             if (binary.Length >= 32)                  return "ERROR";               // It compare the number to . 5.              if (num >= frac)              {                  binary += "1";                  num -= frac;              }              else                         binary += "0";               // Now it become 0.25              frac /= 2;          }          return binary;      }       // Driver Code      public static void Main()      {          double num1 = 0.625; // Input value in Decimal          String output = printBinary(num1);          Console.WriteLine("(0" + output + ") in base 2");           double num2 = 0.72;          output = printBinary(num2);          Console.WriteLine("(" + output + ") ");      }  }   // This code is contributed by mits 
PHP
<?php // PHP program to Binary real number to String.  // Function to convert Binary real // number to String function toBinary($n) {     // Check if the number is Between      // 0 to 1 or Not     if ($n >= 1 || $n <= 0)         return "ERROR";      $frac = 0.5;     $answer = ".";      // Setting a limit on length: 32 characters.              while ($n > 0)     {         // 32 char max         if (strlen($answer) >= 32)             return "ERROR";                      // compare the number to .5         if ($n >= $frac)         {             $answer.="1";             $n = $n - $frac;         }         else         {             $answer.="0";         }                  $frac = ($frac / 2);     }     return $answer; }  // Driver code  // Input value  $n = 0.625;  $result = toBinary($n); print("(0".$result.") in base 2\n");  $m = 0.72; $result = toBinary($m); print("(".$result.")");   // This code is contributed  // by chandan_jnu ?> 
JavaScript
<script>  // Javascript program to Binary real  // number to String.   // Main function to convert Binary // real number to String  function printBinary(num)  {           // Check Number is Between      // 0 to 1 or Not      if (num >= 1 || num <= 0)          return "ERROR";           let binary = "";      let frac = 0.5;      binary += ".";           while (num > 0)      {                   /* Setting a limit on length: 32 characters,          If the number cannot be represented          accurately in binary with at most 32          characters */         if (binary.length >= 32)              return "ERROR";                   // It compare the number to . 5.          if (num >= frac)          {              binary += "1";              num -= frac;          }          else                     binary += "0";                   // Now it become 0.25          frac = frac / 2;      }      return binary;  }   // Driver code  // Input value in Decimal  let num1 = 0.625;  let output = printBinary(num1);  document.write("(0" + output +                 ") in base 2" + "</br>");   let num2 = 0.72;  output = printBinary(num2);  document.write("(" + output + ") ");   // This code is contributed by rameshtravel07  </script> 

Output: 

(0.101)  in base 2 (ERROR)  


Both approaches are equally good; choose the one you feel most comfortable with. 
This article is contributed by Mr. Somesh Awasthi.  


Next Article
Convert from any base to decimal and vice versa

K

kartik
Improve
Article Tags :
  • Mathematical
  • DSA
  • binary-representation
Practice Tags :
  • 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 : NoUsing t
    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 : NoC++#include <ios
    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: 23456
    3 min read
    Check if a large number is divisible by 11 or not
    Given a number in the form of string s, 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: s = "76945"Output: trueExplanation: s when divided by 11 gives 0 as remainder.Input: s = "7695"Out
    5 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 larger number is divisible by 13 or not
    Given a number s represented as a string, determine whether the integer it represents is divisible by 13 or not.Examples : Input: s = "2911285"Output: trueExplanation: 2911285 ÷ 13 = 223945, which is a whole number with no remainder.Input: s = "920"Output: falseExplanation: 920 ÷ 13 = 70.769..., whi
    10 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 : 252Table of Content[Naive Approach] Iterative LCM Calculation - O(n * log(min(a
    14 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: 2Using Recursive GCDThe GCD of three or more numbers equals the product of the pr
    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: 4Explanatio
    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: 1Algorith
    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 MultipleExamples: 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 multiplie
    4 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 integers n and m, construct a strictly increasing sequence of m positive integers with sum exactly equal to n such that the GCD of the sequence is maximized. If multiple sequences have the same maximum GCD, return the lexicographically smallest one. If not possible, return -1.Examples : Input
    7 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^5Examples: 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 : a_{k+1}=\begin{Bmatrix} \lfloor a_{k}^{1/2} \rfloor & for \quad even \quad a
    5 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, 7Expl
    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 = 24Input: 3Output: 246Explanation: For n = 3, the sum of first 3 terms are 2 + 22 + 222 = 246Usin
    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 = 84Input: n = 10 Output: 1330Explanation: sum = 12 + 32 + 52 + 72 + 92 + 112 + 132 + 152 + 172 + 192 = 1 + 9 + 24 + 49 + . . . + 3
    3 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 Cont
    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 L, R 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 Explanation : In the
    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 sideExamples: Input : a = 3, b = 3, k = 1Output : 7Explanation: 3^3 = 27 for k = 1. First digit is 7 in 27Input : a = 5, b = 2, k = 2Output : 2Explanation: 5^2 = 25 for k = 2. First digit is 2 in 25The approach is simple. Computes the
    3 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. \log ^{*}n:=\begin{cases}0n\leq 1;\\1+\log ^{*}(\log n)n>1\end{cases} Applications: It is used in the analysis of algorithms (Refer Wiki for detail
    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
    8 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^3 + 2x^2 + 10x - 20 and three initial guesses - 0, 1 and 2 .Output : The
    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 1
    14 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
    8 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 App
    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 and
    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 pri
    12 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 mult
    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: trueInput: n = 15Output: falseInput: n = 1Output:
    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 2^i - 1 where 0 < i < n , is congruent to n~(mod~(2^n - 1)) . In other words, a number n is prime if and only if.{\displaystyle \prod _{1\leq
    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 fact
    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 still
    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 Positive Number
    Given a positive integer n, find all the distinct divisors of n.Examples:Input: n = 10 Output: [1, 2, 5, 10]Explanation: 1, 2, 5 and 10 are the divisors of 10. Input: n = 100Output: [1, 2, 4, 5, 10, 20, 25, 50, 100]Explanation: 1, 2, 4, 5, 10, 20, 25, 50 and 100 are divisors of 100.Table of Content[
    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)
    Given three integers x, n, and M, compute (x^n) % M (remainder when x raised to the power n is divided by M).Examples : Input: x = 3, n = 2, M = 4Output: 1Explanation: 32 % 4 = 9 % 4 = 1.Input: x = 2, n = 6, M = 10Output: 4Explanation: 26 % 10 = 64 % 10 = 4.Table of Content[Naive Approach] Repeated
    6 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*0 m
    15+ min read
    Modular Division
    Given three positive integers a, b, and M, the objective is to find (a/b) % M i.e., find the value of (a × b-1 ) % M, where b-1 is the modular inverse of b modulo M.Examples: Input: a = 10, b = 2, M = 13Output: 5Explanation: The modular inverse of 2 modulo 13 is 7, so (10 / 2) % 13 = (10 × 7) % 13 =
    13 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 a
    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