Aman and his birthday gift

Today is Aman's birthday but I forgot to bring a gift for him. He is very angry with me. I have an idea for a gift. He likes coding very much. Why not give him a problem to solve as his gift?

Aman likes everything infinite. Now he is studying the properties of a sequence s, such that its first element is equal to an (s1 = a), and the difference between any two neighboring elements is equal to c (si - si - 1 = c). In particular, Aman wonders if his favorite integer b appears in this sequence, that is, there exists positive integer i, such that si = b. Of course, you are the person he asks for help.

Example:

Input:  a = 1, b = 7, c = 3
Output: 1->2->4->5->NULL

Approach

C++

#include <bits/stdc++.h>
using namespace std;

void birthdayGift(int aint bint c)
{
    if (b > a && c <= 0)
        cout << "NO\n";
    else if (b > a)
    {
        int flag = 0;
        while (b > a)
        {
            a = a + c;
            if (a == b)
            {
                flag = 1;
                break;
            }
            else if (a > b)
                break;
        }
        if (flag == 1)
            cout << "YES\n";
        else
            cout << "NO\n";
    }
    else
    {
        if (c >= 0)
            cout << "NO\n";
        else
        {
            int flag = 0;
            while (a > b)
            {
                a = a + c;
                if (b == a)
                {
                    flag = 1;
                    break;
                }
                else if (a < b)
                    break;
            }
            if (flag == 1)
                cout << "YES\n";
            else
                cout << "NO\n";
        }
    }
}
int main()
{
    int a = 1b = 7c = 3;

    birthdayGift(abc);
    return 0;
}


No comments:

Post a Comment