1

Write a program that generates all the factors of a number entered by the user. For instance, the number 12 has the factors 2 * 2 * 3. This program has the following requirements:

  1. The user must enter a positive integer. If the user enters something else, your program should output an error message and let the user enter a new value. Use a do/while loop to make sure the user input is successful.

  2. The factors must be output in increasing order. The lowest factor your program should report is 2.

  3. Your program should output 4 factors per line, each factor in a field of 10 characters. (Hint: the number of factors output determines when to output endl!)

  4. You will need a while loop to report the factors. Here are some helpful hints:

    1. If (a % b == 0) then a is a factor of b.

    2. When you have found a factor, output the factor and then reduce the number you are working with by dividing the number by the factor… ie) b = b / a;

I have this code I can't get it to display the factors. After you enter the number it just ends with out displaying the factors.

#include<iostream>

using namespace std;

int factor(int& n)
{
  for(int k=2; k<=n; k++)
    if(n%k==0)
    {
      n = n/k;
      return k;
    }
}


int main()
{
  int n;
  int p=0;

  do
  {
    cout << "Enter a Positive Integer :";
    cin >> n;
  } while(n<=0);

  cout << "Factors are " << endl;

  while(1)
  {
    if(n==1) break;
    cout << factor(n) << " ";
    p++;
    if(p%4==0) 
      cout << endl;   // new line after every 4 factors !!

    system("pause");
    return 0;
  }
}
8
  • 2
    is it a homework? tag it homework then.
    – phoxis
    Jul 24, 2011 at 8:06
  • 1
    I hope your code is indented better than that!
    – Paul
    Jul 24, 2011 at 8:07
  • Could you also properly indent your code ? It's tough to read like this. Jul 24, 2011 at 8:07
  • I assume the requirement is actually for all the prime factors. After all, 4 and 6 are also factors of 12.
    – Ted Hopp
    Jul 24, 2011 at 8:24
  • 1
    “If (a % b == 0) then a is a factor of b.” This is exactly the contrary: b is a factor of a.
    – Benoit
    Jul 24, 2011 at 8:45

2 Answers 2

5

It's difficult to see due to your (lack of) indentation, but this part :

system("pause");
return 0;

is inside the while(1) loop. It should be outside of the while loop.

0

So after indentation it is clear that :

 while(1)
 {
  if(n==1) break;
  cout << factor(n) << " ";
  p++;
  if(p%4==0) 
    cout << endl;   // new line after every 4 factors !!

  system("pause");
  return 0;
 }

After just calculating and printing the first factor you return from main. So please indent the code and keep proper formatting. Also even if you have single line under if , for etc, enclose them in braces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.