Longest subsequence such that every element in the subsequence is formed by multiplying previous element with a prime | Python3 program to implement the above approach ; Function to pre - store primes ; Sieve method to check if prime or not ; Multiples ; Pre - store all the primes ; Function to find the longest subsequence ; Hash map ; Call the function to pre - store the primes ; Initialize last element with 1 as that is the longest possible ; Iterate from the back and find the longest ; Get the number ; Initialize dp [ i ] as 1 as the element will only me in the subsequence ; Iterate in all the primes and multiply to get the next element ; Next element if multiplied with it ; If exceeds the last element then break ; If the number is there in the array ; Get the maximum most element ; Hash the element ; Find the longest ; Driver Code
from math import sqrt NEW_LINE def SieveOfEratosthenes ( MAX , primes ) : NEW_LINE INDENT prime = [ True ] * ( MAX + 1 ) ; NEW_LINE for p in range ( 2 , int ( sqrt ( MAX ) ) + 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p ** 2 , MAX + 1 , p ) : NEW_LINE INDENT prime [ i ] = False ; NEW_LINE DEDENT DEDENT DEDENT for i in range ( 2 , MAX + 1 ) : NEW_LINE INDENT if ( prime [ i ] ) : NEW_LINE INDENT primes . append ( i ) ; NEW_LINE DEDENT DEDENT DEDENT def findLongest ( A , n ) : NEW_LINE INDENT mpp = { } ; NEW_LINE primes = [ ] ; NEW_LINE SieveOfEratosthenes ( A [ n - 1 ] , primes ) ; NEW_LINE dp = [ 0 ] * n ; NEW_LINE dp [ n - 1 ] = 1 ; NEW_LINE mpp [ A [ n - 1 ] ] = n - 1 ; NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT num = A [ i ] ; NEW_LINE dp [ i ] = 1 ; NEW_LINE maxi = 0 ; NEW_LINE for it in primes : NEW_LINE INDENT xx = num * it ; NEW_LINE if ( xx > A [ n - 1 ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT elif xx in mpp : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , 1 + dp [ mpp [ xx ] ] ) ; NEW_LINE DEDENT DEDENT mpp [ A [ i ] ] = i ; NEW_LINE DEDENT ans = 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = max ( ans , dp [ i ] ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 5 , 6 , 12 , 35 , 60 , 385 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( findLongest ( a , n ) ) ; NEW_LINE DEDENT