C++

C++: Count in Factors

 
 

Write a program which counts up from 1, displaying each number as the multiplication of its prime factors. For the purpose of this task, 1 may be shown as itself.

For examle, 2 is prime, so it would be shown as itself. 6 is not prime; it would be shown as 2\times3. Likewise, 2144 is not prime; it would be shown as 2\times2\times2\times2\times2\times67.

#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;

void getPrimeFactors( int li )
{
	int f = 2; string res;
	if( li == 1 ) res = "1";
	else
	{
		while( true )
		{
			if( !( li % f ) ) 
			{
				stringstream ss; ss << f;
				res += ss.str();
				li /= f; if( li == 1 ) break;
				res += " x ";
			}
			else f++;
		}
	}
	cout << res << "\n";
}

int main( int argc, char* argv[] )
{
	for( int x = 1; x < 101; x++ )
	{
		cout << right << setw( 4 ) << x << ": "; 
		getPrimeFactors( x );
	}
	cout << 2144 << ": "; getPrimeFactors( 2144 );
	cout << "\n\n";
	return system( "pause" );
}
Output:
   1: 1
   2: 2
   3: 3
   4: 2 x 2
   5: 5
   6: 2 x 3
   7: 7
   8: 2 x 2 x 2
   9: 3 x 3
  10: 2 x 5
  11: 11
  12: 2 x 2 x 3
  13: 13
  14: 2 x 7
  15: 3 x 5
  16: 2 x 2 x 2 x 2
  17: 17
  18: 2 x 3 x 3
  19: 19
  20: 2 x 2 x 5
  21: 3 x 7
  22: 2 x 11
  23: 23
  24: 2 x 2 x 2 x 3
  .
  .
  .

SOURCE

Content is available under GNU Free Documentation License 1.2.

  • output_8BgzjE