
- 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
Check If It Is a Good Array in C++
Suppose we have an array called nums of positive integers. We have to select some subset of nums, then multiply each element by an integer and add all these numbers. The array will be a good array if we can get a sum of 1 from the array by any possible subset and multiplicand.
We have to check whether the array is good or not.
So, if the input is like [12,23,7,5], then the output will be True, this is because If we take numbers 5, 7, then 5*3 + 7*(-2) = 1
To solve this, we will follow these steps −
g := nums[0]
for initialize i := 1, when i < size of nums, update (increase i by 1), do −
g := gcd of g and nums[i]
return true when g is 1
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int gcd(int a, int b){ return !b ? a : gcd(b, a % b); } bool isGoodArray(vector<int>& nums){ int g = nums[0]; for (int i = 1; i < nums.size(); i++) g = gcd(g, nums[i]); return g == 1; } }; main(){ Solution ob; vector<int> v = {12,23,7,5}; cout << (ob.isGoodArray(v)); }
Input
{12,23,7,5}
Output
1
- Related Articles
- Check If It Is a Straight Line in C++
- C# program to check if a value is in an array
- Check if an array is stack sortable in C++
- Check if it is possible to sort the array after rotating it in Python
- C++ Program to Check if it is a Sparse Matrix
- Check if a given array is pairwise sorted or not in C++
- Check if an array is synchronized or not in C#
- Check if an array is sorted and rotated in C++
- Check if an array object is equal to another array object in C#
- Check if an array is read-only or not in C#
- JavaScript Program to Check if it is possible to sort the array after rotating it
- Queries to check if it is possible to join boxes in a circle in C++
- How to check if an item exists in a C# array?
- Check if a value is present in an Array in Java
- Check if the array is beautiful in Python

Advertisements