Problem description from an Iranian online course, translated with the help of Google Translate:
Tired of coding, Mehdi has gone on to his childhood games. But because he doesn't know who to play with, he has to change the rules of the game and play solitaire. To begin with, he wants to play solitaire "Walnut, Break Out".
Mehdi is standing n cm from the wall and wants to reach the wall. To do this, he can extend his leg forward, or transverse his leg forward. The goal is for him to stretch his legs and move forward so that he can tangle with the wall at the end. But Mehdi doesn't code anymore, so you need to help him figure out how to win this game. That is, tell him to stretch his leg a few times and cross a few times to get the exact distance. The problem is about checking whether we can get to a wall that is represented with a number, by horizontal and vertical moves or not. If we can, print one of the correct answers and we cant, print -1.
We have three input values: The distance to the wall \$ n \$ , the foot length \$ x\$ , and the foot width \$ y\$ . The values are restricted by $$ 1 \le n,x,y \le 100\,000 \, . $$
We have to check if \$ n \$ is a multiple of \$ x \$ plus a multiple of \$ y \$. For example if \$n = 10 \$and \$x = 2 , y=3\$ , we can reach to \$10\$ with multiplying \$2 \cdot 2 + 3 \cdot 2 \$, or \$2 \cdot 5 + 3 \cdot 0 \$.
I wrote this code for it. I get correct answers for most of the test cases except one, and 2 errors for a time limit exceeded. I am looking for an optimized and faster solution.
#include<iostream>
using namespace std;
int main()
{
int n,x,y;
int x1,y1;
cin>>n>>x>>y;
bool flag = false;
for(int i=0;i<n;i++)
{
for(int j=0;j<n+1;j++)
{
if (x * i + j * y == n)
{
flag = true;
x1=i;
y1=j;
}
}
if(flag)
break;
}
if(flag == false)
cout<<"-1";
else
cout<<x1<<" "<<y1;
return 0;
}