A straight approach would be to check 11, 111, 1111 and so on to be divisible by that number.But that will not be optimal.
Let's say we have a series M(n) which is 11, 111, 1111 and so on.
So M(1) = 11, M(2) = 111 , etc
and lets assume the number we need to check the divisibility is n.
If M(i) mod n = 0, then you're done (M(i) is the answer), so let's assume it's not.
You want to find M(i+1) mod n.
Since M(i+1) = 10 * M(i) + 1, you can easily calculate
M(i+1) mod n = (10 * (M(i) mod n) + 1) mod n
int count=1, rem=1;
while(rem)
{
rem= (rem*10+1)%n;
Let's say we have a series M(n) which is 11, 111, 1111 and so on.
So M(1) = 11, M(2) = 111 , etc
and lets assume the number we need to check the divisibility is n.
If M(i) mod n = 0, then you're done (M(i) is the answer), so let's assume it's not.
You want to find M(i+1) mod n.
Since M(i+1) = 10 * M(i) + 1, you can easily calculate
M(i+1) mod n = (10 * (M(i) mod n) + 1) mod n
Hence the code
while(rem)
{
rem= (rem*10+1)%n;
count++;
}
while(count--)
{
cout<<"1";
}
}
while(count--)
{
cout<<"1";
}
No comments:
Post a Comment