
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Convert the array such that the GCD of the array becomes 1 in C++
In this tutorial, we will be discussing a program to convert the array such that the GCD of the array becomes one.
For this we will be provided with an array and a positive integer k. Our task is to convert the array elements such that the GCD of elements is 1 while only dividing the array elements by k any number of times until the element is less than k.
Example
#include <bits/stdc++.h> using namespace std; //calculating the GCD of array int calculate_gcd(int* arr, int n){ int gcd = arr[0]; for (int i = 1; i < n; i++) gcd = __gcd(arr[i], gcd); return gcd; } //checking if the operation is possible bool convertGcd(int* arr, int n, int k){ int gcd = calculate_gcd(arr, n); int max_prime = 1; for (int i = 2; i <= sqrt(gcd); i++) { while (gcd % i == 0) { gcd /= i; max_prime = max(max_prime, i); } } max_prime = max(max_prime, gcd); return (max_prime <= k); } int main(){ int arr[] = { 10, 15, 30 }; int k = 6; int n = sizeof(arr) / sizeof(arr[0]); if (convertGcd(arr, n, k) == true) cout << "Yes"; else cout << "No"; return 0; }
Output
Yes
- Related Articles
- Array with GCD of any of its subset belongs to the given array?
- Rearrange an array such that ‘arr[j]’ becomes ‘i’ if ‘arr[i]’ is ‘j’ in C++
- Add minimum number to an array so that the sum becomes even in C++?
- Find the minimum value to be added so that array becomes balanced in C++
- GCD of an array of numbers in java
- Add minimum number to an array so that the sum becomes even in C programming
- Find minimum value to assign all array elements so that array product becomes greater in C++
- Convert array of object to array of array in JavaScript
- Find an element in array such that sum of left array is equal to sum of right array using c++
- Count the number of sub-arrays such that the average of elements present in the subarray is greater than that not present in the sub-array in C++
- Find GCD of factorial of elements of given array in C++
- Maximize the sum of array by multiplying prefix of array with -1 in C++
- Rearrange an array such that arr[i] = i in C++
- Find a permutation such that number of indices for which gcd(p[i], i) > 1 is exactly K in C++
- Find the GCD that lies in given range

Advertisements