View Single Post
Old 02-27-2005, 08:46 PM   #10 (permalink)
Rekna
Junkie
 
A couple optimizations for you stiltzkin

when you find a prime remove as many of that prime as possible from the list then start searching at that number plus 2, don't start back at 2. Also don't increment i by one instead increament it by 2 (making sure it is odd to start).

Here is what I came up with in 3 minutes. I don't actually save the primes but one could easily add the code to save them in a few minutes.

Code:
#include <iostream>
using namespace std;

int main()
{
	unsigned  int n;
	cout << "Enter a positive number: ";
	cin >> n;
	cout << "The prime factors are:\n1 ";

	//remove 2's
	while(n%2==0)
	{
		cout << "2 ";
		n/=2;
	}
	int p=3;
	//remove odd numbers
	while(n!=1)
	{
		while(n%p==0)
		{
			cout << p << " ";
			n/=p;
		}
		p+=2;
	}
	cout << endl;
}

Last edited by Rekna; 02-27-2005 at 08:58 PM..
Rekna is offline  
 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62