Sherlock and The Beast

Sherlock Holmes suspects his archenemy Professor Moriarty is once again plotting something diabolical. Sherlock's companion, Dr. Watson, suggests Moriarty may be responsible for MI6's recent issues with their supercomputer, The Beast.

Shortly after resolving to investigate, Sherlock receives a note from Moriarty boasting about infecting The Beast with a virus. He also gives him a clue: an integer. Sherlock determines the key to removing the virus is to find the largest Decent Number having that number of digits.

Decent Number has the following properties:

  1. Its digits can only be 3's and/or 5's.
  2. The number of 3's it contains is divisible by 5.
  3. The number of 5's it contains is divisible by 3.
  4. It is the largest such number for its length.

Moriarty's virus shows a clock counting down to The Beast's destruction, and time is running out fast. Your task is to help Sherlock find the key before The Beast is destroyed!

For example, the numbers  and  are both decent numbers because there are  's and  's in the first, and  's in the second. They are the largest values for those length numbers that have proper divisibility of digit occurrences.

Example:

Input:  n = 3
Output: 555

Approach

C++

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

void decentNumber(int n)
{
    if (n < 3)
        cout << "-1";
    else if (n % 3 == 0)
    {
        for (int i = 0i < ni++)
            cout << '5';
    }
    else
    {
        int a = 5;
        while (n - a > 0)
        {
            if ((n - a) % 3 != 0)
                a += 5;
            else
                break;
        }
        if (n - a >= 0)
        {
            for (int i = 0i < n - a; ++i)
                cout << '5';
            for (int i = 0i < a; ++i)
                cout << '3';
        }
        else
            cout << "-1";
    }
    cout << '\n';
}

int main()
{

    int n = 3;
    decentNumber(n);

    return 0;
}


No comments:

Post a Comment