日期:2014-05-18 浏览次数:20897 次
using System; using System.Collections.Generic; namespace ConsoleApplication1 { class Program { /// <summary> /// get the prime factors of <paramref name="value"/> /// </summary> /// <param name="value">the value to get prime factors of</param> /// <returns>prime factors stored in a list</returns> static List<uint> GetFactors(uint value) { List<uint> factors = new List<uint>(); // list of factors to return List<uint> primes = new List<uint>(); // prime numbers encountered uint k = 2; // initial prime number primes.Add(k); // load the first prime number to the prime list while (true) { if (value == k) { factors.Add(k); break; } else if (value % k == 0) { factors.Add(k); value /= k; } else { bool isPrime; do { k+=2; isPrime = true; foreach (uint prime in primes) { // k is divisible by 'prime' // k is not a prime number if (k % prime == 0) { isPrime = false; break; } if (prime > Math.Sqrt(k)) { // no need to check other numbers break; } } } while (!isPrime); primes.Add(k); // add k to the list } } return factors; } static void Main(string[] args) { Console.Write("Input a number: "); string input = Console.ReadLine(); uint value = Convert.ToUInt32(input); List<uint> factors = GetFactors(value); Console.Write("{0} = ", value); for (int i = 0; i < factors.Count - 1; i++) { Console.Write("{0} * ", factors[i]); // print the factors except for the last } Console.WriteLine("{0}", factors[factors.Count - 1]); // print the last factor } } }
------解决方案--------------------
static List<int> GetPrimes(int m) { List<int> primes = new List<int>(); for (int i = 2; i <= m; ) { if (IsPrime(i) && m % i == 0) { primes.Add(i); m /= i; } else { i++; } } return primes; } static bool IsPrime(int m) { if (m == 2) return true; if (m == 1 || m % 2 == 0