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
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Generate an array having sum of Euler Totient Function of all elements equal to N
Next article icon

Count of non co-prime pairs from the range [1, arr[i]] for every array element

Last Updated : 10 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of  N integers, the task for every ith element of the array is to find the number of non co-prime pairs from the range [1, arr[i]].

Examples:

Input: N = 2, arr[] = {3, 4}
Output: 2 4
Explanation:

  1. All non-co-prime pairs from the range [1, 3] are (2, 2) and (3, 3).
  2. All non-co-prime pairs from the range [1, 4] are (2, 2), (2, 4), (3, 3) and (4, 4).

Input: N = 3, arr[] = {5, 10, 20}
Output: 5 23 82

Naive Approach: The simplest approach to solve the problem is to iterate over every ith array element and then, generate every possible pair from the range [1, arr[i]], and for every pair, check whether it is non-co-prime, i.e. gcd of the pair is greater than 1 or not.

Follow the steps below to solve this problem:

  • Iterate over the range [0, N - 1] using a variable, say i, and perform the following steps: 
    • Initialize variables lastEle as arr[i] and count as 0 to store the last value of the current range and number of co-prime pairs respectively.
    • Iterate over every pair from the range [1, arr[i]] using variables x and y and do the following:
      • If GCD(x, y) is greater than 1, then the increment count by 1.
    • Finally, print the count as the answer.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Recursive function to // return gcd of two numbers int gcd(int a, int b) {     if (b == 0)         return a;      return gcd(b, a % b); }  // Function to count the number of // non co-prime pairs for each query void countPairs(int* arr, int N) {      // Traverse the array arr[]     for (int i = 0; i < N; i++) {          // Stores the count of         // non co-prime pairs         int count = 0;          // Iterate over the range [1, x]         for (int x = 1; x <= arr[i]; x++) {              // Iterate over the range [x, y]             for (int y = x; y <= arr[i]; y++) {                  // If gcd of current pair                 // is greater than 1                 if (gcd(x, y) > 1)                     count++;             }         }         cout << count << " ";     } }  // Driver Code int main() {     // Given Input     int arr[] = { 5, 10, 20 };     int N = 3;      // Function Call     countPairs(arr, N);      return 0; } 
Java
// Java program for the above approach import java.util.*;  class GFG{  // Recursive function to // return gcd of two numbers static int gcd(int a, int b) {     if (b == 0)         return a;      return gcd(b, a % b); }  // Function to count the number of // non co-prime pairs for each query static void countPairs(int[] arr, int N) {          // Traverse the array arr[]     for(int i = 0; i < N; i++)      {                  // Stores the count of         // non co-prime pairs         int count = 0;          // Iterate over the range [1, x]         for(int x = 1; x <= arr[i]; x++)          {                          // Iterate over the range [x, y]             for(int y = x; y <= arr[i]; y++)              {                                  // If gcd of current pair                 // is greater than 1                 if (gcd(x, y) > 1)                     count++;             }         }         System.out.print(count + " ");     } }  // Driver Code public static void main(String[] args) {          // Given Input     int arr[] = { 5, 10, 20 };     int N = 3;      // Function Call     countPairs(arr, N); } }  // This code is contributed by subhammahato348 
Python3
# Python3 program for the above approach  # Recursive program to # return gcd of two numbers def gcd(a, b):          if b == 0:         return a              return gcd(b, a % b)  # Function to count the number of # non co-prime pairs for each query def countPairs(arr, N):          # Traverse the array arr[]     for i in range(0, N):                # Stores the count of         # non co-prime pairs         count = 0                  # Iterate over the range [1,x]         for x in range(1, arr[i] + 1):                          # Iterate over the range [x,y]             for y in range(x, arr[i] + 1):                                # If gcd of current pair                 # is greater than 1                 if gcd(x, y) > 1:                     count += 1                              print(count, end = " ")  # Driver code if __name__ == '__main__':        # Given Input     arr = [ 5, 10, 20 ]     N = len(arr)      # Function Call     countPairs(arr, N)  # This code is contributed by MuskanKalra1 
C#
// C# program for the above approach using System;  class GFG{  // Recursive function to // return gcd of two numbers static int gcd(int a, int b) {     if (b == 0)         return a;      return gcd(b, a % b); }  // Function to count the number of // non co-prime pairs for each query static void countPairs(int[] arr, int N) {          // Traverse the array arr[]     for(int i = 0; i < N; i++)      {                  // Stores the count of         // non co-prime pairs         int count = 0;          // Iterate over the range [1, x]         for(int x = 1; x <= arr[i]; x++)          {                          // Iterate over the range [x, y]             for(int y = x; y <= arr[i]; y++)              {                                  // If gcd of current pair                 // is greater than 1                 if (gcd(x, y) > 1)                     count++;             }         }         Console.Write(count + " ");     } }  // Driver Code public static void Main(String[] args) {          // Given Input     int []arr = { 5, 10, 20 };     int N = 3;      // Function Call     countPairs(arr, N); } }  // This code is contributed by shivanisinghss2110 
JavaScript
<script>  // JavaScript program for the above approach  // Recursive function to // return gcd of two numbers function gcd(a, b) {     if (b == 0)         return a;      return gcd(b, a % b); }  // Function to count the number of // non co-prime pairs for each query function countPairs(arr, N) {          // Traverse the array arr[]     for(var i = 0; i < N; i++)      {                  // Stores the count of         // non co-prime pairs         var count = 0;          // Iterate over the range [1, x]         for(var x = 1; x <= arr[i]; x++)          {                          // Iterate over the range [x, y]             for(var y = x; y <= arr[i]; y++)              {                                  // If gcd of current pair                 // is greater than 1                 if (gcd(x, y) > 1)                     count++;             }         }         document.write(count + " ");     } }  // Driver Code  // Given Input var arr = [ 5, 10, 20 ]; var N = 3;  // Function Call countPairs(arr, N);  // This code is contributed by shivanisinghss2110  </script> 

Output
5 23 82 

Time Complexity: O(N*M2*log(M)), where M is the maximum element of the array.
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized by using Euler's totient function, and prefix sum array. Follow the steps below to solve the problem: 

  • Initialize two arrays, say phi[] and ans[] as 0, where the ith element of the array represents the count of integers that is coprime to i and the count of non-coprime pairs formed from the range [1, arr[i]].
  • Iterate over the range [1, MAX] using a variable, say i, and assign i to phi[i].
  • Iterate over the range [2, MAX] using a variable, say i,  and perform the following steps:
    • If phi[i] = i, then iterate over the range [i, MAX] using a variable j and perform the following steps:
      • Decrement phi[j] / i from phi[j] and then increment j by i.
  • Iterate over the range [1, MAX] using a variable, say i,  and perform the following steps:
    • Update ans[i] to ans[i - 1] + (i - phi[i]).
  • Finally, after completing the above steps, print the array ans[].

Below is the implementation of the above approach: 

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; const int MAX = 1005;  // Auxiliary function to pre-compute // the answer for each array void preCalculate(vector<int>& phi,                   vector<int>& ans) {     phi[0] = 0;     phi[1] = 1;      // Iterate over the range [1, MAX]     for (int i = 2; i <= MAX; i++)         phi[i] = i;      // Iterate over the range [1, MAX]     for (int i = 2; i <= MAX; i++) {          // If the number is prime         if (phi[i] == i) {              for (int j = i; j <= MAX; j += i)                  // Subtract the number of                 // pairs which has i as one                 // of their factors                 phi[j] -= (phi[j] / i);         }     }      // Iterate over the range [1, MAX]     for (int i = 1; i <= MAX; i++)         ans[i] = ans[i - 1] + (i - phi[i]); }  // Function to count the number of // non co-prime pairs for each query void countPairs(int* arr, int N) {     // The i-th element stores     // the count of element that     // are co-prime with i     vector<int> phi(1e5, 0);      // Stores the resulting array     vector<int> ans(1e5, 0);      // Function Call     preCalculate(phi, ans);      // Traverse the array arr[]     for (int i = 0; i < N; ++i) {         cout << ans[arr[i]] << " ";     } }  // Driver Code int main() {     // Given Input     int arr[] = { 5, 10, 20 };     int N = 3;      // Function Call     countPairs(arr, N); } 
Java
// Java program for the above approach import java.util.*; class GFG {      static int MAX = 1005;  // Auxiliary function to pre-compute // the answer for each array static void preCalculate(int[] phi,                   int[] ans) {     phi[0] = 0;     phi[1] = 1;      // Iterate over the range [1, MAX]     for (int i = 2; i <= MAX; i++)         phi[i] = i;      // Iterate over the range [1, MAX]     for (int i = 2; i <= MAX; i++) {          // If the number is prime         if (phi[i] == i) {              for (int j = i; j <= MAX; j += i)                  // Subtract the number of                 // pairs which has i as one                 // of their factors                 phi[j] -= (phi[j] / i);         }     }      // Iterate over the range [1, MAX]     for (int i = 1; i <= MAX; i++)         ans[i] = ans[i - 1] + (i - phi[i]); }  // Function to count the number of // non co-prime pairs for each query static void countPairs(int[] arr, int N) {     // The i-th element stores     // the count of element that     // are co-prime with i     int[] phi = new int[100000];     Arrays.fill(phi, 0);      // Stores the resulting array     int[] ans = new int[100000];     Arrays.fill(ans, 0);          // Function Call     preCalculate(phi, ans);      // Traverse the array arr[]     for (int i = 0; i < N; ++i) {         System.out.print(ans[arr[i]] + " ");     } }     // Driver Code public static void main(String[] args) {      // Given Input     int arr[] = { 5, 10, 20 };     int N = 3;      // Function Call     countPairs(arr, N); } }  // This code is contributed by code_hunt. 
Python3
MAX = 1005;  def preCalculate(phi,ans):     phi[0] = 0     phi[1] = 1          # Iterate over the range [1, MAX]     for i in range(2, MAX+1):         phi[i] = i          # Iterate over the range [1, MAX]      for i in range(2, MAX+1):         if (phi[i] == i):             for j in range(i, MAX+1, i):                                  # Subtract the number of                 # pairs which has i as one                 # of their factors                 phi[j] -= (phi[j] // i);                      # Iterate over the range [1, MAX]     for i in range(1, MAX+1):         ans[i] = ans[i - 1] + (i - phi[i]);  # Function to count the number of # non co-prime pairs for each query def countPairs(arr, N):      # The i-th element stores     # the count of element that     # are co-prime with i     phi = [0 for i in range(100001)]      # Stores the resulting array     ans = [0 for i in range(100001)]      # Function Call     preCalculate(phi, ans);      # Traverse the array arr[]     for i in range(N):         print(ans[arr[i]],end=' ');  # Given Input arr= [5, 10, 20] N = 3;  # Function Call countPairs(arr, N);  # This code is contributed by rutvik_56. 
C#
// C# program for the above approach using System; class GFG{  static int MAX = 1005;  // Auxiliary function to pre-compute // the answer for each array static void preCalculate(int[] phi,                   int[] ans) {     phi[0] = 0;     phi[1] = 1;      // Iterate over the range [1, MAX]     for (int i = 2; i <= MAX; i++)         phi[i] = i;      // Iterate over the range [1, MAX]     for (int i = 2; i <= MAX; i++) {          // If the number is prime         if (phi[i] == i) {              for (int j = i; j <= MAX; j += i)                  // Subtract the number of                 // pairs which has i as one                 // of their factors                 phi[j] -= (phi[j] / i);         }     }      // Iterate over the range [1, MAX]     for (int i = 1; i <= MAX; i++)         ans[i] = ans[i - 1] + (i - phi[i]); }  // Function to count the number of // non co-prime pairs for each query static void countPairs(int[] arr, int N) {     // The i-th element stores     // the count of element that     // are co-prime with i     int[] phi = new int[100000];     Array.Clear(phi, 0, 100000);      // Stores the resulting array     int[] ans = new int[100000];     Array.Clear(ans, 0, 100000);      // Function Call     preCalculate(phi, ans);      // Traverse the array arr[]     for (int i = 0; i < N; ++i) {         Console.Write(ans[arr[i]] + " ");     } }  // Driver Code public static void Main() {     // Given Input     int[] arr = { 5, 10, 20 };     int N = 3;      // Function Call     countPairs(arr, N); } }  // This code is contributed by sanjoy_62. 
JavaScript
<script>  // JavaScript program for the above approach  const MAX = 1005;  // Auxiliary function to pre-compute // the answer for each array function preCalculate(phi, ans) {   phi[0] = 0;   phi[1] = 1;    // Iterate over the range [1, MAX]   for (let i = 2; i <= MAX; i++) phi[i] = i;    // Iterate over the range [1, MAX]   for (let i = 2; i <= MAX; i++) {     // If the number is prime     if (phi[i] == i) {       for (let j = i; j <= MAX; j += i)         // Subtract the number of         // pairs which has i as one         // of their factors         phi[j] -= Math.floor(phi[j] / i);     }   }    // Iterate over the range [1, MAX]   for (let i = 1; i <= MAX; i++)    ans[i] = ans[i - 1] + (i - phi[i]); }  // Function to count the number of // non co-prime pairs for each query function countPairs(arr, N) {   // The i-th element stores   // the count of element that   // are co-prime with i   let phi = new Array(1e5).fill(0);    // Stores the resulting array   let ans = new Array(1e5).fill(0);    // Function Call   preCalculate(phi, ans);    // Traverse the array arr[]   for (let i = 0; i < N; ++i) {     document.write(ans[arr[i]] + " ");   } }  // Driver Code  // Given Input let arr = [5, 10, 20]; let N = 3;  // Function Call countPairs(arr, N);  </script> 

Output
5 23 82 

Time Complexity: O(N+ M*log(N)), where M is the maximum element of the array.
Auxiliary Space: O(M+N)


 


Next Article
Generate an array having sum of Euler Totient Function of all elements equal to N

S

shekabhi1208
Improve
Article Tags :
  • Mathematical
  • DSA
  • Arrays
  • prefix-sum
  • HCF
  • euler-totient
Practice Tags :
  • Arrays
  • Mathematical
  • prefix-sum

Similar Reads

    Euler Totient for Competitive Programming
    What is Euler Totient function(ETF)?Euler Totient Function or Phi-function for 'n', gives the count of integers in range '1' to 'n' that are co-prime to 'n'. It is denoted by \phi(n) .For example the below table shows the ETF value of first 15 positive integers: 3 Important Properties of Euler Totie
    8 min read
    Euler's Totient Function
    Given an integer n, find the value of Euler's Totient Function, denoted as Φ(n). The function Φ(n) represents the count of positive integers less than or equal to n that are relatively prime to n. Euler's Totient function Φ(n) for an input n is the count of numbers in {1, 2, 3, ..., n-1} that are re
    10 min read
    Count of non co-prime pairs from the range [1, arr[i]] for every array element
    Given an array arr[] consisting of N integers, the task for every ith element of the array is to find the number of non co-prime pairs from the range [1, arr[i]]. Examples: Input: N = 2, arr[] = {3, 4}Output: 2 4Explanation: All non-co-prime pairs from the range [1, 3] are (2, 2) and (3, 3).All non-
    13 min read
    Generate an array having sum of Euler Totient Function of all elements equal to N
    Given a positive integer N, the task is to generate an array such that the sum of the Euler Totient Function of each element is equal to N. Examples: Input: N = 6Output: 1 6 2 3 Input: N = 12Output: 1 12 2 6 3 4 Approach: The given problem can be solved based on the divisor sum property of the Euler
    5 min read
    Count all possible values of K less than Y such that GCD(X, Y) = GCD(X+K, Y)
    Given two integers X and Y, the task is to find the number of integers, K, such that gcd(X, Y) is equal to gcd(X+K, Y), where 0 < K <Y. Examples: Input: X = 3, Y = 15Output: 4Explanation: All possible values of K are {0, 3, 6, 9} for which GCD(X, Y) = GCD(X + K, Y). Input: X = 2, Y = 12Output:
    8 min read
    Count of integers up to N which are non divisors and non coprime with N
    Given an integer N, the task is to find the count of all possible integers less than N satisfying the following properties: The number is not coprime with N i.e their GCD is greater than 1.The number is not a divisor of N. Examples: Input: N = 10 Output: 3 Explanation: All possible integers which ar
    5 min read
    Find the number of primitive roots modulo prime
    Given a prime p . The task is to count all the primitive roots of p .A primitive root is an integer x (1 <= x < p) such that none of the integers x - 1, x2 - 1, ...., xp - 2 - 1 are divisible by p but xp - 1 - 1 is divisible by p . Examples: Input: P = 3 Output: 1 The only primitive root modul
    5 min read
    Compute power of power k times % m
    Given x, k and m. Compute (xxxx...k)%m, x is in power k times. Given x is always prime and m is greater than x. Examples: Input : 2 3 3 Output : 1 Explanation : ((2 ^ 2) ^ 2) % 3 = (4 ^ 2) % 3 = 1 Input : 3 2 3 Output : 0 Explanation : (3^3)%3 = 0 A naive approach is to compute the power of x k time
    15+ min read
    Primitive root of a prime number n modulo n
    Given a prime number n, the task is to find its primitive root under modulo n. The primitive root of a prime number n is an integer r between[1, n-1] such that the values of r^x(mod n) where x is in the range[0, n-2] are different. Return -1 if n is a non-prime number. Examples: Input : 7 Output : S
    15 min read
    Euler's Totient function for all numbers smaller than or equal to n
    Euler's Totient function ?(n) for an input n is the count of numbers in {1, 2, 3, ..., n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. For example, ?(4) = 2, ?(3) = 2 and ?(5) = 4. There are 2 numbers smaller or equal to 4 that are relatively pri
    13 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