0

I'm trying to solve a problem from hacker rank over here.

The question is:

enter image description here

So to solve this, I tried with a simple maths equation:

4x + 7y = lucky_number

For example, to check 15 is a lucky_number or not, I could do start with x, y values 0 and substituting in the above equation until its equal or greater than (if so stop and say its not lucky number)

The above logic works fine. But the problem is with big number, imagine to check number 966888032206353 lucky or not, starting with x,y to 0 wont be an efficient idea.

Any guidance to it?

batman
  • 3,565
  • 5
  • 20
  • 41

4 Answers4

1

Another way to think of it: All you need to do is plot the line

7y = -4x + 966888032206353

and identify any points where both x and y are integers.

So, you don't need a nested loop. Instead:

  1. Iterate y as an integer. for y=0; y<966888032206353 / 7; y++

  2. For each iteration, solve for x, using floating point math.

  3. If x is an integer, the number is lucky.

This will require about 138T iterations.

John Wu
  • 50,556
  • 8
  • 44
  • 80
1

All numbers from 7*4=28 up (in fact even all mumbers from 18 up) are lucky, for the rest just precompute a smalll table.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
1

Here's my code that I submitted to Hackerrank.

#include <bits/stdc++.h>
using namespace std;
int q; long long n; bool dp[1009];
int main() {
    cin >> q;
    dp[0] = true;
    for(int i = 1; i <= 1000; i++) {
        if(i >= 4 && dp[i - 4]) dp[i] = true;
        if(i >= 7 && dp[i - 7]) dp[i] = true;
    }
    while(q--) {
        cin >> n;
        if(n >= 1000 || dp[n]) cout << "Yes" << endl;
        else cout << "No" << endl;
    }
}

This is dynamic programming, but if n >= 28 it is always ok.

square1001
  • 1,402
  • 11
  • 26
0

One of your problems is that your problem description is very incomplete. You can infact represent any integer number as 4x + 7y, if you only allowed negative x and y. For example, 1 = 4*2 + (-1)*7 and you can get a solution for any number by multiplying with that factor.

I guess the best solution from an algorithmics point of view is to use dynamic programming. You can simply start checking numbers whether they are lucky in your sense or not. As soon as you find 4 consequtive lucky numbers, you can stop, because any number afterwards will be lucky by just adding 4 an appropriate number of times. I guess you will find a sequence of 4 consequtive lucky numbers very early.

Georg
  • 5,626
  • 1
  • 23
  • 44