Calculate the Nth term || Hacker Rank

 Question 16 || Hacker Rank

Calculate the Nth term || Hacker Rank

Calculate the Nth term



Objective

This challenge will assist you with learning the idea of recursion.

 

A capability that calls itself is known as a recursive capability. The C programming language upholds recursion. Yet, while utilizing recursion, one should be mindful so as to characterize a leave condition from the capability, any other way it will go into a limitless circle.

 

To forestall boundless recursion, articulation (or comparable methodology) can be utilized where one branch settles on the recursive decision and other doesn't.

 

void recurse() {

    .....

    recurse()//recursive call

    .....

}

int fundamental() {

    .....

    recurse();//capability call

    .....

}

 

Task

There is a series, , where the following term is the amount of pervious three terms. Given the initial three terms of the series, , , and individually, you need to yield the nth term of the series utilizing recursion.

Recursive strategy for computing nth term is given beneath.

Calculate the Nth term


 Input Configuration

The primary line contains a solitary whole number, .

 

The following line contains 3 space-isolated numbers, , , and .

 

Imperatives

Calculate the Nth term


 Yield Configuration

 

Print the nth term of the series, .

 

Test Info 0

5

1 2 3

 

Test Result 0

11

 

Clarification 0

Think about the accompanying advances:

 

From steps , , , and , we can say ; then utilizing the qualities from step , , , and , we get . Consequently, we print as our response.

Calculate the Nth term



#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
//Complete the following function.

int find_nth_term(int n, int a, int b, int c) {
  int term, t1 = a, t2 = b, t3 = c;
    if (n == 1)
        term = t1;
    else if (n == 2)
        term = t2;
    else if (n == 3)
        term = t3;
    else {
        for (int i = 4; i <= n; i++) {
            term = t1 + t2 + t3;
            t1 = t2;
            t2 = t3;
            t3 = term;
        }
    }
    return term;
}

int main() {
    int n, a, b, c;
  
    scanf("%d %d %d %d", &n, &a, &b, &c);
    int ans = find_nth_term(n, a, b, c);
 
    printf("%d", ans); 
    return 0;
}



Output:

Calculate the Nth term



Post a Comment

0 Comments