![]() |
Given an array arr[] containing integers of size N and a number k, the task is to find the XOR of array elements that are divisible by a given number k in Python. Examples: Input: arr[] = {3, 9, 16, 12, 13, 15} , k = 3 Output: 25 Explanation: Only 3,9,12,15 are divisible by 3, XOR = 3^9^12^15 = 9 Input: arr[] = { 3, 9, 12, 13, 15, 2 , 6, 18 } , k=2 Output: Explanation: Only 12,2,6,18 are divisible by 2, XOR= 12^2^6^18 = 26 Approach:In order to find the XOR of numbers that are divisible by a given number in the array, we simply iterate through the array and find if an element is divisible by k or not, and then we XOR using the ‘^’ operator. Therefore, the following steps are followed to compute the answer:
Below is the implementation of the above approach: Python3
Output
26 Complexity Analysis: Time Complexity: O(n) Space Complexity: O(1) Method 2: Using the filter() function : Step-by-Step Approach :
Python3
Output
26 Complexity Analysis: Time Complexity: O(n) This is because the filter function takes O(n) time to create the iterator containing the elements that are divisible by the given number, where n is the length of the input array. Now the for loop iterates over the numbers that are divisible by divisor for a constant number of iteration, so we can say that the overall time complexity will be O(n). Space Complexity: O(1) This is because we are only using few variables to store the input array, the divisor, divisible_sum, and the Gfgresult and the space used by these variables does not depend on the size of the input array. So we can say that the overall space complexity will be O(1). Method #3: using bit manipulation
Python3
Output
26 The time complexity is O(n * log(max_num)), where n is the length of the input array and max_num is the maximum value in the input array. The space complexity is O(1) because we only use a fixed number of variables. |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |