这个算法的目的是求一个数因数的个数。算法原理是先求出质因数的个数。假设这个数是x。p1,p2,...pn是x的质因数。则x=p1y1*p2y2*p3y3*...*pnyn 。那么根据乘法原理,x的因数的个数就是(y1+1)*(y2+1)*...*(yn+1)。
- //the result is 76576500
- using System.Collections.Generic;
- using System;
- class Factors
- {
- public static void Main()
- {
- int i=1;
- int sum=0;
- while (true)
- {
- sum+=i;
- if(FactorsCount(sum)>500)
- {
- Console.WriteLine(sum);
- break;
- }
- i++;
- }
- }
- public static int FactorsCount(int n)
- {
- Dictionary<int,int> primeFactors=new Dictionary<int,int>();
- int i=2;
- while(i<=n)
- {
- if (n % i ==0)
- {
- if (primeFactors.ContainsKey(i))
- {
- primeFactors[i]++;
- }
- else
- {
- primeFactors[i]=1;
- }
- n=n / i;
- }
- else
- {
- i++;
- }
- }
- int product=1;
- ICollection<int> keys=primeFactors.Keys;
- foreach ( int key in keys )
- {
- product*=(primeFactors[key]+1);
- }
- return product;
- }
- }