Wednesday, 27 Oct 2021

# Number of subarrays consisting only of Pronic Numbers

Number of subarrays consisting only of Pronic Numbers
Given an array arr[] consisting of N positive integers, the task is to count the number of subarrays consisting only of pronic numbers.
Examples:

Input: arr[] = {5, 6, 12, 3, 4}Output: 3Explanation: The subarray that consists only of pronic numbers are:
{6}
{12}
{6, 12}
Therefore, the total count of such subarrays is 3.
Input: arr[] = {0, 4, 20, 30, 5}Output: 4

Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays of the given array and count those subarrays made up of pronic numbers only. After checking for all the subarrays, print the count obtained.Time Complexity: O(√M * N3), where M is the maximum element present in the arrayAuxiliary Space: O(N)
Efficient Approach: The above approach can be optimized by keeping the track of continuous sequences of pronic numbers and then, count the number of subarrays formed.Follow the steps below to solve the problem:
Initialize a variable, say count, to store the total count of subarrays, and a variable C, to store the count of continuous array elements which are pronic numbers.
Traverse the given array arr[] and perform the following steps:
If the current element arr[i] is a pronic number, then increment C by 1.
Otherwise, increment count by C * (C – 1)/2 to count the number of subarrays with C elements having pronic numbers and update C to 0.

Increment the value of count as C*(C – 1)/2.
After completing the above steps, print the value of count as the result.
Below is the implementation of the above approach:

Python3

def isPronic(n):

for i in range(int(n ** (1 / 2)) + 1):

if i * (i + 1) == n:
return True

return False

def countSub(arr):

ans = 0

ispro = 0

for i in arr:

if isPronic(i):
ispro += 1
else:
ispro = 0

ans += ispro

return ans

arr = [5, 6, 12, 3, 4]
print(countSub(arr))

Time Complexity: O(N*sqrt(M)), where M is the maximum element present in the array.Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.