Skip to main content
4 of 9
added 396 characters in body
Deduplicator
  • 19.3k
  • 1
  • 31
  • 65

Well, there's lots to improve about your program.

  1. Consider adopting any of the common styles for code-formatting.
    As-is, your current formatting seriously impedes readability.

  2. #include <bits/stdc++.h> is a bad idea, sharply limiting portability ad increasing compile-times. See: How does #include <bits/stdc++.h> work in C++?
    Just include those headers you need, which are <vector> and <iostream>.

  3. You are courting conflicting symbols and general bafflement with any minor change of your toolchain. See: Why is using namespace std; considered bad practice?

  4. You are using the popular for-if-antipattern. See Introducing the for-if anti-pattern
    Why don't you just enumerate the ones you are actually interested in?

  5. A for-range-loop is simpler than explicitly using iterators/indices. Unless you actually need them.

  6. In the end you don't actually want that whole list, only whether one of them divides your input-number. So why store them at all, and why also those bigger than the input-number?

  7. return 0; is implicit for main in C++.

Doing it as it should be done, on coliru:

#include <stdio.h>

int luckydiv_helper(long in, long num, int free) {
    return !free
        ? !(in % num)
        : luckydiv_helper(in, 10 * num + 4, free - 1)
            || luckydiv_helper(in, 10 * num + 7, free - 1);
}

int luckydiv(long in) {
    long abort = in;
    for(int digits = 1; abort; digits++, abort /= 10)
        if(luckydiv_helper(in, 0, digits))
            return 1;
    return !in;
}

int main() {
    long in;
    if(scanf("%ld", &in) != 1 || in < -999999999 || in > 999999999) {
        fprintf(stderr, "You didn't enter a number between -999999999 and "
            "+999999999. Aborting.\n");
        // A long can represent all 9-digit decimal numbers.
        return 1;
    }
    printf("%ld ", in);
    if(in < 0) in = -in;
    puts(luckydiv(in) ? "YES" : "NO");
}

A way to efficiently get all "lucky" numbers:

#include <limits>
#include <vector>

template<class T> std::vector<T> luckyvector() {
    std::vector<T> v = {4, 7};
    const auto limit4 = (std::numeric_limits<T>::max() - 4) / 10;
    const auto limit7 = (std::numeric_limits<T>::max() - 7) / 10;
    T x = 0;
    for(size_t i = 0; (x = v[i]) <= limit7; i++) {
        v.push_back(x * 10 + 4);
        v.push_back(x * 10 + 7);
    }
    if(x > limit7 && x <= limit4)
        v.push_pack(x * 10 + 4);
    return v;
}
Deduplicator
  • 19.3k
  • 1
  • 31
  • 65