代码改变世界

【欧拉3】最大质因数

2012-03-09 19:05  撞破南墙  阅读(471)  评论(0编辑  收藏  举报

 

 

 

问题描述:

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

 

public class Q3 {

      /// <summary>
      /// 取得最大的质因数
      /// </summary>
      /// <param name="max">The max.</param>
      /// <returns></returns>
      public static long q3(long max) {
          //遍历可能的质因数2 到。。
          List<long> math = new List<long>();
          for (long i = 2;max != 1; i++) {

              while (max % i == 0) {
                  math.Add(i);
                  max = max / i;
              }

          }
          return math.Distinct().Max();
      }

      public static void test() {
          var t1 = DateTime.Now;
          Console.WriteLine(" " + q3(600851475143) + " cast time " + (DateTime.Now - t1).TotalSeconds);

      }
  }

 

image