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:
How to Find the Smallest Number in an Array in C++?
Next article icon

Smallest integer > 1 which divides every element of the given array

Last Updated : 22 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[], the task is to find the smallest possible integer (other than 1) which divides every element of the given array.

Examples:  

Input: arr[] = { 2, 4, 8 } 
Output: 2 
2 is the smallest possible number which divides the whole array.

Input: arr[] = { 4, 7, 5 } 
Output: -1 
There's no integer possible which divides the whole array other than 1.  

Approach: We know that the GCD of the whole array will be the greatest integer that will divide every element of the array. If GCD = 1 then there's no integer possible that divides the whole array. However, if GCD > 1 then there exists integer(s) which divides the array completely. For example,  

If GCD = 36 then 
36 divides the whole array. 
18 divides the whole array. 
12 divides the whole array. 
9 divides the whole array. 
... 
1 divides the whole array.
Thus, we see that all factors of 36 also divide the array. The smallest prime factor of 36 i.e. 2 is the smallest possible integer which divides the whole array. Hence, we need to find the smallest prime factor of the GCD as the required answer. 

Below is the implementation of the above approach:  

C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std;  // Function to find the smallest divisor  int smallestDivisor(int x)  {      // if divisible by 2      if (x % 2 == 0)          return 2;         // iterate from 3 to sqrt(n)      for (int i = 3; i * i <= x; i += 2) {          if (x % i == 0)              return i;      }         return x;  }   // Function to return smallest possible integer // which divides the whole array int smallestInteger(int* arr, int n) {     // To store the GCD of all the array elements     int gcd = 0;     for (int i = 0; i < n; i++)         gcd = __gcd(gcd, arr[i]);      // Return the smallest prime factor     // of the gcd calculated     return smallestDivisor(gcd); }  // Driver code int main() {     int arr[] = { 2, 4, 8 };     int n = sizeof(arr) / sizeof(arr[0]);     cout << smallestInteger(arr, n);      return 0; } 
Java
// Java implementation of the approach class GFG {  static int __gcd(int a, int b)  {      if (b == 0)          return a;      return __gcd(b, a % b);       }   // Function to find the smallest divisor  static int smallestDivisor(int x)  {      // if divisible by 2      if (x % 2 == 0)          return 2;       // iterate from 3 to sqrt(n)      for (int i = 3; i * i <= x; i += 2)      {          if (x % i == 0)              return i;      }       return x;  }   // Function to return smallest possible integer // which divides the whole array static int smallestInteger(int []arr, int n) {     // To store the GCD of all the array elements     int gcd = 0;     for (int i = 0; i < n; i++)         gcd = __gcd(gcd, arr[i]);      // Return the smallest prime factor     // of the gcd calculated     return smallestDivisor(gcd); }  // Driver code public static void main(String[] args) {     int []arr = { 2, 4, 8 };     int n = arr.length;     System.out.println(smallestInteger(arr, n)); } }  // This code is contributed by Code_Mech. 
Python3
# Python3 implementation of the approach  from math import sqrt, gcd  # Function to find the smallest divisor  def smallestDivisor(x) :          # if divisible by 2      if (x % 2 == 0) :         return 2;           # iterate from 3 to sqrt(n)      for i in range(3, int(sqrt(x)) + 1, 2) :         if (x % i == 0) :             return i;           return x   # Function to return smallest possible  # integer which divides the whole array  def smallestInteger(arr, n) :          # To store the GCD of all the     # array elements      __gcd = 0;      for i in range(n) :         __gcd = gcd(__gcd, arr[i]);       # Return the smallest prime factor      # of the gcd calculated      return smallestDivisor(__gcd);   # Driver code  if __name__ == "__main__" :       arr = [ 2, 4, 8 ];     n = len(arr);          print(smallestInteger(arr, n));   # This code is contributed by Ryuga 
C#
// C# implementation of the approach using System;  class GFG {  static int __gcd(int a, int b)  {      if (b == 0)          return a;      return __gcd(b, a % b);       }   // Function to find the smallest divisor  static int smallestDivisor(int x)  {      // if divisible by 2      if (x % 2 == 0)          return 2;       // iterate from 3 to sqrt(n)      for (int i = 3; i * i <= x; i += 2)      {          if (x % i == 0)              return i;      }       return x;  }   // Function to return smallest possible integer // which divides the whole array static int smallestInteger(int []arr, int n) {     // To store the GCD of all the array elements     int gcd = 0;     for (int i = 0; i < n; i++)         gcd = __gcd(gcd, arr[i]);      // Return the smallest prime factor     // of the gcd calculated     return smallestDivisor(gcd); }  // Driver code static void Main() {     int []arr = { 2, 4, 8 };     int n = arr.Length;     Console.WriteLine(smallestInteger(arr, n)); } }  // This code is contributed by mits 
PHP
<?php // PHP implementation of the approach function gcd($a, $b) {     // Everything divides 0     if($b == 0)         return $a;      return gcd($b , $a % $b); }  // Function to find the smallest divisor function smallestDivisor($x) {     // if divisible by 2     if ($x % 2 == 0)         return 2;      // iterate from 3 to sqrt(n)     for ($i = 3; $i < sqrt($x) + 1; $i += 2)     {         if ($x % $i == 0)             return $i;     }     return $x; }  // Function to return smallest possible // integer which divides the whole array function smallestInteger($arr, $n) {          // To store the GCD of all the     // array elements     $__gcd = 0;     for ($i = 0; $i < $n; $i++)      {         $__gcd = gcd($__gcd, $arr[$i]);     }          // Return the smallest prime factor     // of the gcd calculated     return smallestDivisor($__gcd); }      // Driver code $arr = array(2, 4, 8); $n = count($arr);  echo smallestInteger($arr, $n);  // This code is contributed by Srathore ?> 
JavaScript
<script>     // Javascript implementation of the approach     function __gcd(a, b)      {          if (b == 0)              return a;          return __gcd(b, a % b);       }       // Function to find the smallest divisor      function smallestDivisor(x)      {          // if divisible by 2          if (x % 2 == 0)              return 2;           // iterate from 3 to sqrt(n)          for (let i = 3; i * i <= x; i += 2)          {              if (x % i == 0)                  return i;          }           return x;      }       // Function to return smallest possible integer     // which divides the whole array     function smallestInteger(arr, n)     {              // To store the GCD of all the array elements         let gcd = 0;         for (let i = 0; i < n; i++)             gcd = __gcd(gcd, arr[i]);          // Return the smallest prime factor         // of the gcd calculated         return smallestDivisor(gcd);     }          let arr = [ 2, 4, 8 ];     let n = arr.length;     document.write(smallestInteger(arr, n));  // This code is contributed by divyeshrabadiya07. </script> 

Output
2

Time Complexity: O(n*(log(min(a, b))))
Auxiliary Space: O(1)

For multiple queries, we can precompute the smallest prime factors for numbers to a maximum value using a sieve.  

C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std;  const int MAX = 100005;  // To store the smallest prime factor int spf[MAX];  // Function to store spf of integers void sieve() {     memset(spf, 0, sizeof(spf));     spf[0] = 1;      // When gcd is 1 then the answer is -1     spf[1] = -1;     for (int i = 2; i * i < MAX; i++) {         if (spf[i] == 0) {             for (int j = i * 2; j < MAX; j += i) {                 if (spf[j] == 0) {                     spf[j] = i;                 }             }         }     }     for (int i = 2; i < MAX; i++) {         if (!spf[i])             spf[i] = i;     } }  // Function to return smallest possible integer // which divides the whole array int smallestInteger(int* arr, int n) {      // To store the GCD of all the array elements     int gcd = 0;     for (int i = 0; i < n; i++)         gcd = __gcd(gcd, arr[i]);      // Return the smallest prime factor     // of the gcd calculated     return spf[gcd]; }  // Driver code int main() {     sieve();     int arr[] = { 2, 4, 8 };     int n = sizeof(arr) / sizeof(arr[0]);     cout << smallestInteger(arr, n);      return 0; } 
Java
// Java implementation of the approach class GFG  {  static int MAX = 100005;   // To store the smallest prime factor  static int spf[] = new int[MAX];   // Function to store spf of integers  static void sieve()  {      spf[0] = 1;       // When gcd is 1 then the answer is -1      spf[1] = -1;      for (int i = 2; i * i < MAX; i++)      {          if (spf[i] == 0)          {              for (int j = i * 2; j < MAX; j += i)             {                  if (spf[j] == 0)                  {                      spf[j] = i;                  }              }          }      }      for (int i = 2; i < MAX; i++)      {          if (spf[i] != 1)              spf[i] = i;      }  }   // Function to return smallest possible integer  // which divides the whole array  static int smallestInteger(int[] arr, int n)  {       // To store the GCD of all the array elements      int gcd = 0;      for (int i = 0; i < n; i++)          gcd = __gcd(gcd, arr[i]);       // Return the smallest prime factor      // of the gcd calculated      return spf[gcd];  }  static int __gcd(int a, int b)  {      if (b == 0)          return a;      return __gcd(b, a % b);       }  // Driver code  public static void main(String[] args)  {     sieve();      int arr[] = { 2, 4, 8 };      int n = arr.length;      System.out.println(smallestInteger(arr, n));  } }  /* This code contributed by PrinciRaj1992 */ 
Python3
# Python3 implementation of the approach MAX = 10005;  # To store the smallest prime factor spf = [0] * MAX;  # Function to store spf of integers def sieve():      spf[0] = 1;      # When gcd is 1 then the answer is -1     spf[1] = -1;     i = 2;     while (i * i < MAX):         if (spf[i] == 0):             for j in range(i * 2, MAX, i):                  if (spf[j] == 0):                     spf[j] = i;         i += 1;          for i in range(2, MAX):         if (spf[i] == 0):             spf[i] = i;  # find gcd of two no def __gcd(a, b):      if (b == 0):          return a;      return __gcd(b, a % b);   # Function to return smallest possible integer # which divides the whole array def smallestInteger(arr, n):          # To store the GCD of all the array elements     gcd = 0;     for i in range(n):         gcd = __gcd(gcd, arr[i]);      # Return the smallest prime factor     # of the gcd calculated     return spf[gcd];  # Driver code sieve(); arr = [ 2, 4, 8 ]; n = len(arr); print(smallestInteger(arr, n));  # This code is contributed by mits 
C#
// C# implementation of above approach  using System;      class GFG  {  static int MAX = 100005;   // To store the smallest prime factor  static int []spf = new int[MAX];   // Function to store spf of integers  static void sieve()  {      spf[0] = 1;       // When gcd is 1 then the answer is -1      spf[1] = -1;      for (int i = 2; i * i < MAX; i++)      {          if (spf[i] == 0)          {              for (int j = i * 2; j < MAX; j += i)             {                  if (spf[j] == 0)                  {                      spf[j] = i;                  }              }          }      }      for (int i = 2; i < MAX; i++)      {          if (spf[i] != 1)              spf[i] = i;      }  }   // Function to return smallest possible integer  // which divides the whole array  static int smallestInteger(int[] arr, int n)  {       // To store the GCD of all the array elements      int gcd = 0;      for (int i = 0; i < n; i++)          gcd = __gcd(gcd, arr[i]);       // Return the smallest prime factor      // of the gcd calculated      return spf[gcd];  }  static int __gcd(int a, int b)  {      if (b == 0)          return a;      return __gcd(b, a % b);       }  // Driver code  public static void Main(String[] args)  {     sieve();      int []arr = { 2, 4, 8 };      int n = arr.Length;      Console.WriteLine(smallestInteger(arr, n));  } }  // This code has been contributed by 29AjayKumar 
PHP
<?php // PHP implementation of the approach  $MAX = 10005;  // To store the smallest prime factor $spf = array_fill(0, $MAX, 0);  // Function to store spf of integers function sieve() {     global $spf, $MAX;     $spf[0] = 1;      // When gcd is 1 then the answer is -1     $spf[1] = -1;     for ($i = 2; $i * $i < $MAX; $i++)     {         if ($spf[$i] == 0)          {             for ($j = $i * 2; $j < $MAX; $j += $i)              {                 if ($spf[$j] == 0)                  {                     $spf[$j] = $i;                 }             }         }     }     for ($i = 2; $i < $MAX; $i++)      {         if (!$spf[$i])             $spf[$i] = $i;     } }  // find gcd of two no function __gcd($a, $b)  {      if ($b == 0)          return $a;      return __gcd($b, $a % $b);       }   // Function to return smallest possible integer // which divides the whole array function smallestInteger($arr, $n) {     global $spf, $MAX;          // To store the GCD of all the array elements     $gcd = 0;     for ($i = 0; $i < $n; $i++)         $gcd = __gcd($gcd, $arr[$i]);      // Return the smallest prime factor     // of the gcd calculated     return $spf[$gcd]; }  // Driver code sieve(); $arr = array( 2, 4, 8 ); $n = count($arr); echo smallestInteger($arr, $n);  // This code is contributed by mits ?> 
JavaScript
<script>     // Javascript implementation of above approach          let MAX = 100005;       // To store the smallest prime factor     let spf = new Array(MAX);      // Function to store spf of integers     function sieve()     {         spf[0] = 1;          // When gcd is 1 then the answer is -1         spf[1] = -1;         for (let i = 2; i * i < MAX; i++)         {             if (spf[i] == 0)             {                 for (let j = i * 2; j < MAX; j += i)                 {                     if (spf[j] == 0)                     {                         spf[j] = i;                     }                 }             }         }         for (let i = 2; i < MAX; i++)         {             if (spf[i] != 1)                 spf[i] = i;         }     }      // Function to return smallest possible integer     // which divides the whole array     function smallestInteger(arr, n)     {          // To store the GCD of all the array elements         let gcd = 0;         for (let i = 0; i < n; i++)             gcd = __gcd(gcd, arr[i]);          // Return the smallest prime factor         // of the gcd calculated         return spf[gcd];     }      function __gcd(a, b)     {         if (b == 0)             return a;         return __gcd(b, a % b);         }          sieve();     let arr = [ 2, 4, 8 ];     let n = arr.length;     document.write(smallestInteger(arr, n));  </script> 

Output
2

Next Article
How to Find the Smallest Number in an Array in C++?
author
rohan23chhabra
Improve
Article Tags :
  • Algorithms
  • Mathematical
  • Competitive Programming
  • C++ Programs
  • DSA
  • divisibility
  • GCD-LCM
Practice Tags :
  • Algorithms
  • Mathematical

Similar Reads

  • Find elements of an array which are divisible by N using STL in C++
    Given an array and an integer N, find elements which are divisible by N, using STL in C++ Examples: Input: a[] = {1, 2, 3, 4, 5, 10}, N = 2 Output: 3 Explanation: As 2, 4, and 10 are divisible by 2 Therefore the output is 3 Input:a[] = {4, 3, 5, 9, 11}, N = 5 Output: 1 Explanation: As only 5 is divi
    2 min read
  • Count of elements on the left which are divisible by current element
    Given an array A[] of N integers, the task is to generate an array B[] such that B[i] contains the count of indices j in A[] such that j < i and A[j] % A[i] = 0Examples: Input: arr[] = {3, 5, 1} Output: 0 0 2 3 and 5 do not divide any element on their left but 1 divides 3 and 5.Input: arr[] = {8,
    5 min read
  • How to Find the Smallest Number in an Array in C++?
    In C++, arrays are the data types that store the collection of the elements of other data types such as int, float, etc. In this article, we will learn how to find the smallest number in an array using C++. For Example,Input: myVector = {10, 3, 10, 7, 1, 5, 4} Output: Smallest Number = 1Find the Sma
    2 min read
  • Count of multiples in an Array before every element
    Given an array arr of size N, the task is to count the number of indices j (j<i) such that a[i] divides a[j], for all valid indexes i. Examples: Input: arr[] = {8, 1, 28, 4, 2, 6, 7} Output: 0, 1, 0, 2, 3, 0, 1 No of multiples for each element before itself – N(8) = 0 () N(1) = 1 (8) N(28) = 0 ()
    12 min read
  • Reduce the array to atmost one element by the given operations
    Given an array of integers arr[], the task is to find the remaining element in the array after performing the following operations: In each turn, choose the two maximum integers X and Y from the array.If X == Y, remove both elements from the array.If X != Y, insert an element into the array equal to
    7 min read
  • Smallest element present in every subarray of all possible lengths
    Given an array arr[] of length N, the task for every possible length of subarray is to find the smallest element present in every subarray of that length. Examples: Input: N = 10, arr[] = {2, 3, 5, 3, 2, 3, 1, 3, 2, 7}Output: -1-1 3 2 2 2 1 1 1 1Explanation:For length = 1, no element is common in ev
    15+ min read
  • Length of longest subarray whose sum is not divisible by integer K
    Given an array arr[] of size N and an integer k, our task is to find the length of longest subarray whose sum of elements is not divisible by k. If no such subarray exists then return -1.Examples: Input: arr[] = {8, 4, 3, 1, 5, 9, 2}, k = 2 Output: 5 Explanation: The subarray is {8, 4, 3, 1, 5} with
    10 min read
  • Minimum possible sum of array elements after performing the given operation
    Given an array arr[] of positive integers and an integer x, the task is to minimize the sum of elements of the array after performing the given operation at most once. In a single operation, any element from the array can be divided by x (if it is divisible by x) and at the same time, any other elem
    8 min read
  • Minimum elements inserted in a sorted array to form an Arithmetic progression
    Given a sorted array arr[], the task is to find minimum elements needed to be inserted in the array such that array forms an Arithmetic Progression.Examples: Input: arr[] = {1, 6, 8, 10, 14, 16} Output: 10 Explanation: Minimum elements required to form A.P. is 10. Transformed array after insertion o
    8 min read
  • Min operations to reduce N to 1 by multiplying by A or dividing by B
    Given a number N and two integers A and B, the task is to check if it is possible to convert the number to 1 by the following two operations: Multiply it by ADivide it by B If it is possible to reduce N to 1 then print the minimum number of operations required to achieve it otherwise print "-1". Exa
    8 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