Home > Mobile >  How to find the smallest number composed of only 1 that can divide by n, given n is a coprime of 10?
How to find the smallest number composed of only 1 that can divide by n, given n is a coprime of 10?

Time:09-12

I'm writing a program with which to find the smallest number m composed of only the number "1" that can divide by a given number n. n must be a co-prime of 10.

For example:

  • n = 37 -> m = 111 (111/37 =3)
  • n = 11 -> m = 1111 (1111/11 = 101)
  • n = 91 -> m = 111111 (111111/91 = 1221)

My current code:

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

int main()
{
    long long int n, m = 1;
    cin>>n;
    while (m % n != 0) {
        m = m*10   1;
    }
    cout<<m;
}

I believe this is the right way to find m, but it runs into TLE (Time Limit Exceeded) problems, and I assume it's because:

  • The code takes too many loops to find a number m that satisfies the conditions.
  • There is no number m that satisfies the conditions.

Is there anyway to avoid TLE issues for this program? And is there anyway to mathematically find m based on n, or that number m does not exist?

I've found the solutions for Time Limit Exceeded error.

The solution was to reduce the steps in the while loop to:

  while(m%n!=0)
{
        m=(m*10 1)%n;
        cout<<"1";
}

Despite this being solved, I am still curious about the way to find m mathematically (or to determine whether m exists), so any other inputs regarding this are appreciated.

CodePudding user response:

For the new version you found, you can be sure that there's no solution if the new m you computed was already encountered previously - that means you're on an infinite loop.

However, since caching previous values of m can be too much for the scope of this problem, you can resort to the weaker condition: if the loop run for more than n times - since m is always smaller than n, it means that at least one m value must have already repeated.

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

int main()
{
    unsigned long int n = 12, m = 1;
    unsigned int count = 0;
    string result = "1";
    while(m%n!=0 && count < n){
        m=(m*10 1)%n;
        result = result   "1";
        count  ;
    }
    cout << (m%n == 0 ? result : "no result") << endl;
}

The condition is weaker in the sense that you find out that there's no solution later, but the result is still correct.

  • Related