Given three integers ‘A’ denotes the primary time period of an arithmetic sequence, ‘C’ denotes the widespread distinction between an arithmetic sequence and an integer ‘B’, the duty is to inform whether or not ‘B’ exists within the arithmetic sequence or not. Return 1 if B is current within the sequence. In any other case, returns 0.
Examples:
Enter: A = 1, B = 3, C = 2
Output: 1
Rationalization: 3 is the second time period of the sequence beginning with 1 and having a typical distinction 2.Enter: A = 1, B = 2, C = 3
Output: 0
Rationalization: 2 shouldn’t be current within the sequence.
Strategy: To resolve the issue comply with the beneath concept:
To resolve this downside you need to use the idea of Arithmetic Development. That’s nth time period of an Arithmetic sequence beginning with ‘a’ and customary distinction ‘d’ is a + (n-1)*d.
Observations:
- The primary time period is A. If B is bigger than A, then C should be constructive.
- If B is lesser than A, then C should be unfavourable.
- Suppose d = distinction between A and B. If B needs to exist within the arithmetic sequence, d should be divisible by C.
Under are the steps for the above strategy:
- Initialize a variable say, d that can retailer the distinction between B and A.
- Examine if B is the same as A, then the time period b is legitimate,
- Examine if d < 0, then the widespread distinction should be unfavourable and d should be divisible by the widespread distinction, if each will not be the case, return 0.
- if(C ≥ 0), return 0.
- if(dpercentC == 0), return 1.
- If d is bigger than or equal to 0, then the widespread distinction should be larger than 0 and d should be divisible by the widespread distinction, if each shouldn’t be the case, return 0.
- if(C ≤ 0), return 0.
- if(dpercentC == 0), return 1.
- Else, return 0.
Under is the code for the above strategy:
C++
|
|
Time Complexity: O(1)
Auxiliary Area: O(1)