Homework 16 Solution

 

This program is missing the definition of the function firstfactor. Complete the program by defining the function (a description of what the function is supposed to do is given in the source code's comments). When your program is working correctly, a typical run might look like this:

Enter an integer larger than 1: 60
The factorization of 60 is (2)(2)(3)(5)
 

Turn in a printout of your program and a screenshot showing it running on 21978 

 

/*******************************************
** This program reads an integer from the
** user and prints out its factorization
** into irreducibles. Unfortunately, I've
** been unable to figure out how to implement
** the function firstfactor, which takes an
** integer n, where n > 1, and returns the
** smallest factor of n, i.e. the smallest
** integer greater than 1 that divides n
** evenly. You need to add the definition
** of firstfactor.
*******************************************/
#include <iostream>
using namespace std;
 
/*******************************************
** PROTOTYPE
*******************************************/
int firstfactor(int);
 
/*******************************************
** MAIN FUNCTION
*******************************************/
int main(){
    // Get integer n, n > 1, from user
    int n;
    cout << "Enter an integer larger than 1: ";
    cin >> n;
 
    // Print out factorization
    cout << "The factorization of " << n << " is ";
    while(n > 1){
        // get & print next irreducible factor
        int f = firstfactor(n);
        cout << '(' << f << ')';
        n = n / f;
    }
    cout << endl;
 
    return 0;
}
 
/*******************************************
** FUNCTION DEFINITION
*******************************************/
 
int firstfactor (int n)
{
        int div=2;
        while (n%div != 0)
        {
               div++;
        }
 
        return div;
}

syntax highlighted by Code2HTML, v. 0.9.1