- 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

Suppose we have an array nums with positive values. We have to find the number of different GCDs among all non-empty subsequences of nums. As we know the GCD of a sequence of numbers is the greatest value that divides all the numbers in the sequence evenly.

So, if the input is like nums = [4,6,18], then the output will be 4 because gcd([4]) = 4, gcd([6]) = 6, gcd([18]) = 18 gcd([4,6]) = 2, gcd([4,18]) = 2, gcd([6,18]) = 6, gcd([4,6,18]) = 2 so all numbers are [4,6,18,2], there are 4 numbers.

To solve this, we will follow these steps −

T := maximum of nums + 1

nums := a new set containing all distinct numbers of nums

ans := 0

for x in range 1 to T - 1, do

g := 0

for y in range x to T - 1, update in each step by x, do

if y is in nums, then

g := gcd(g, y)

if g is same as x, then

come out from loops

if g is same as x, then

ans := ans + 1

return ans

Let us see the following implementation to get better understanding

from math import gcd def solve(nums): T = max(nums) + 1 nums = set(nums) ans = 0 for x in range(1, T): g = 0 for y in range(x, T, x): if y in nums: g = gcd(g, y) if g == x: break if g == x: ans += 1 return ans nums = [4,6,18] print(solve(nums))

[4,6,18]

4

- Related Questions & Answers
- Program to find number of distinct subsequences in Python
- Program to find number of increasing subsequences of size k in Python
- Program to find number of arithmetic subsequences from a list of numbers in Python?
- Program to find number of subsequences that satisfy the given sum condition using Python
- Program to find number of unique subsequences same as target in C++
- Program to find number of consecutive subsequences whose sum is divisible by k in Python
- Analysis of Different Methods to find Prime Number in Python program
- Program to find number of different substrings of a string for different queries in Python
- Different Methods to find Prime Number in Python Program
- Program to find number of subsequences with i, j and k number of x, y, z letters in Python
- Program to find number of different integers in a string using Python
- Program to find maximize palindrome length from subsequences in Python
- Program to find sum of widths of all subsequences of list of numbers in Python
- Analysis of Different Methods to find Prime Number in Python
- Program to count number of unique subsequences of a string in C++

Advertisements