Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my method for finding all divisors for two numbers isn't working

So I made a while loop for finding all divisors for given numbers and it’s the following

int a,b;
int temp =0;
cout << "Enter the first number : ";
cin  >> a;
cout << "Enter the second number : ";
cin >> b;
int smallestNum = a<b?a:b;
while(true)
    {
        temp++;
        if(a%temp == 0 && b%temp == 0) cout << temp << ", ";
        if (temp == smallestNum) break;
    }
    cout << "are all the divisors for both numbers";

and it worked like expected but when i tried to do the same in a for loop it didn’t go as planned

int a,b;
int temp;
cout << "Enter the first number : ";
cin  >> a;
cout << "Enter the second number : ";
cin  >> b;
temp = a<b?a:b;
for (int i; i == temp; i++)
{
    if(a%i==0 && b%i==0) cout << i << ", ";
}
cout << "are all the divisors for both numbers";

I can’t even find the problem in my code to fix it, how can I fix it????

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

for loop will iterate as long as condition is true, your condition is i == temp which is (in general) false, you should change it to i != temp

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading