
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- Check If It Is a Straight Line in C++
- C++ Program to Check if it is a Sparse Matrix
- Check if it is possible to sort the array after rotating it in Python
- C# program to check if a value is in an array
- Check if an array is stack sortable in C++
- Python and multi-threading. Is it a good idea?
- 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++
- Queries to check if it is possible to join boxes in a circle in C++
- Check if a File is hidden in C#
- Check if a number is Palindrome in C++
- Check if a Matrix is Invertible in C++
- Check if a number is Bleak in C++
- C++ code to check given matrix is good or not
Advertisements