user17286002
user17286002

Reputation: 23

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

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:

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:

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.

Upvotes: 1

Views: 131

Answers (1)

kikon
kikon

Reputation: 8620

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.

Upvotes: 1

Related Questions