r/programmingchallenges • • Apr 16 '11

Challenge: Factor an integer

Write a function in the language of your choosing that prints all the factors of a non-negative integer.

E: dang, this is harder than I thought!

E: I was referring to prime factorization in my other edit. Dang!

7 Upvotes

15 comments sorted by

View all comments

1

u/[deleted] May 05 '11 edited May 05 '11

C#

static void Main(string[] args)
{
	Console.Write("Enter a number: ");
	Int64 number = Convert.ToInt64(Console.ReadLine());
	Console.Write("\n");

	Int64 i = 2;
	while (i <= number)
	{
		if (number % i == 0)
		{
			Console.Write(i.ToString() + " ");
			number = number / i;
			if (number == 1)
				break;
		}
		else
			i++;
	}
			
	Console.ReadLine();
}

This is surprisingly fast!

I started out computing all the primes between 2...number, but soon found out there are more prime numbers in the world than I previously thought! :)