
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find number of different subsequences GCDs in Python
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
Example
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))
Input
[4,6,18]
Output
4
- Related Articles
- 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 consecutive subsequences whose sum is divisible by k 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 subsequences with i, j and k number of x, y, z letters in Python
- Different Methods to find Prime Number in Python Program
- Analysis of Different Methods to find Prime Number in Python program
- Program to find maximize palindrome length from subsequences in Python
- Program to find number of different substrings of a string for different queries in Python
- Program to find number of different integers in a string using Python
- Program to find sum of widths of all subsequences of list of numbers in Python
- Program to count number of unique subsequences of a string in C++
- Program to find number of sublists that contains exactly k different words in Python
