Ian Lundberg
Ian Lundberg

Reputation: 1883

how to get the factors of a product

I am trying to write a piece of code that will take the number let's say 24 and get all the factors for it so it would print the numbers 1 and 24, 8 and 3, etc. I tried doing this myself however I am fairly new to using c++ so it kind of confuses me a little. I apologize if this is really easy or simple to answer. could you please show me how this could be done?

int y = 0;
int x = 0;
int product = x * y;

while (true)
{
    product = x * y;
    x++;
    y++;
    if (product == 24)
    {
        cout << x << " " << y << endl;
    }
}

that is the code I tried doing it with but I realized that since x and y are increasing at the same time it will never reach 24 as a product.

Upvotes: 0

Views: 211

Answers (4)

Faruk Sahin
Faruk Sahin

Reputation: 8726

Here is a quick code snippet :

for (int i = 1; i <= n; ++i) { 
    if (n % i == 0) {
        std::cout << i;
    }
}

Note that it is not optimized.

Upvotes: 1

Foteini
Foteini

Reputation: 11

You should start x and y on opposite directions. (i.e x=1 and y=24) and moving them closer to each other until you reach the median (i.e 12). e.g

  1. x=1 y=24 --> product=24,
  2. x=1, y=23 --> product=23<24 so x++
  3. x=2, y=23 --> product=46>24 so y--
  4. x=2, y=22 --> product ...

It is more algorithmic what you ask rather than c++.

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182761

Rather than y++, try y = 24 / x. Just start x at 1, not zero!

So:

x++;               // do this first, so x isn't zero
y = 24 / x;       // get closest y, rounding down
product = x * y; // see if it works
if (product == 24)
  ...

Upvotes: 1

RonaldBarzell
RonaldBarzell

Reputation: 3830

You will want to loop from 1 to that number; if the number you are testing, modulo your current loop index is 0, then it is a factor.

This is readily translated into code. Here's a hint: % is the modulo operator.

If a specific step trips you up, feel free to ask here. But try to translate the above first.

Upvotes: 0

Related Questions