Laboratory 3 Solutions
Solution to primes.cc code:
/******************************************************************* * Name: Brenda Student * Date: 2/6/14 * Course: CSCI 132 Section 01 * Assignment: Lab 3 * Instructor: Royden * Program: primes.cc * Purpose: Compute prime factors of a given integer. ********************************************************************/ #include "stack.h" int main(void) { int number; //number to find prime factors of int factor, result; //Variables for testing factors Stack primeStack; //Stack to hold factors as they're found cout << "Enter an integer: " << endl; cin >> number; result = number; for (factor = 2; factor <= number; factor++ ) { while (result%factor == 0) { result = result/factor; primeStack.push(factor); } //end while } //end for /************************************************************ Some alternatives for the above loop: while (factor <= result ) { if (result%factor == 0) { primeStack.push(factor); result = result/factor; } else { factor++; } //end if-else } //end while ******************************************************* while (result > 1 ) { while (result%factor == 0) { primeStack.push(factor); result = result/factor; } //end inner while factor++; } //end outer while **********************************************************/ cout << "The prime factors of " << number << " are " << endl; while (! primeStack.empty() ) { primeStack.top(factor); cout << factor << " "; primeStack.pop(); } //end while loop cout << endl; } //end main
Home | | Syllabus | | Assignments | | Lecture Notes