Finding a smallest positive number that is evenly divisible by all numbers from 1 to z.

Oct 8, 2015 at 8:16pm
Hello! I created this account exclusively to ask for help. I started learning C++ a few days ago and I have found a website (projecteuler.net) that gives questions about math and the most efficient way of finding out the answer is writing a program. I completed the first 3 problems, skipped the 4th and now I am attempting to solve the 5th. It asks for a smallest positive number that is evenly divisible by all numbers from 1 to 20 (I replaced that with z to give some flexibility to my program).

So anyway, this is the program I wrote to find out the number:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;
int main()
{
    int x, y, i, z;
    cout << "Enter z:\n";
    cin >> z;
    for (x=1;;x++) //x is supposed to be the number I'm asked to find, this is setup to run forever until it finds it.
    {
        y = 0; //setting the number of times x mod i = 0 to 0.
        for (i=1;i=z;i++) //i is supposed to be the number I'm dividing x by, in the case of this particular question, 1 to 20.
        {
            if (x % i == 0) //checks if x mod i = 0, if so
            {
                y++; //adds a 1 to the counter.
            }
        }
        if (y == z) //if counter y is equal to z, the biggest divisor
        {
            cout << x << endl; //output the answer that is x to the console
            return 0; //and stop the program.
        }
    }
}


In my mind, this should work perfectly, but when I run it and enter the z variable (even if it is something extremely small, like 4), it doesn't output anything else, it just sits there. Could anyone point out my mistake? Thanks!
Oct 8, 2015 at 9:12pm
The second for loop is wrong, you are assigning not comparing this is a huge mistake as c++ compilers won't complain if you replaced a condition with assignment statement.

You need to understand for loops more, check the tutorial on this site.

As for the condition it should be for (i=1;i<=z;++i)

One last thing, you can use break instead of return 0.
Last edited on Oct 8, 2015 at 9:13pm
Oct 8, 2015 at 9:14pm
On line 10 you wrote 'i = z' instead of 'i == z'. This is still wrong, since the loop will run as long as the condition is true. If z > 1, then the loop will not run at all, leaving y in its original value of z, making the condition on line 18 always false, causing the program to hang.
i <= z is the condition you want.
Oct 9, 2015 at 4:20am
Thank you both, CodeBlob and helios, that works perfectly. I'll be sure to check out the for loops tutorial!
Topic archived. No new replies allowed.