2009年3月21日 星期六

Project Euler 003.c


  1 |  /*///-----------------------------------------------------------------
  2 |   *  Project Euler Problem 003
  3 |   *  File Name   : pe-003.c
  4 |   *  Author      : Yen-Chin,Lee
  5 |   *  Email       : coldnew.tw@gmail.com
  6 |   *  Create Date : 2009/03/21 19:05:37
  7 |   *  Description :
  8 |   *  Compile Opt : gcc pe-003.c -std=c99 -o 003
  9 |   *  Problem :
 10 |   *
 11 |   *  The prime factors of 13195 are 5, 7, 13 and 29.
 12 |   *  What is the largest prime factor of the number 600851475143 ?
 13 |  /*///---------------------------- Copyright (C) ,2009 coldnew --------
 14 |  
 15 |  #include <stdio.h>
 16 |  #include <stdlib.h>
 17 |  #include <stdbool.h>
 18 |  
 19 |  bool isPrime (unsigned long long testNum)
 20 |  {
 21 |          if (1 == testNum){
 22 |                  return false;
 23 |          }
 24 |          for(int i =2 ; i <= (testNum / 2) ; i++){
 25 |                  if (0 == testNum % i) {
 26 |                          return false;
 27 |                  } else {
 28 |                          return true;
 29 |                  }                
 30 |          }
 31 |  }
 32 |  
 33 |  int main( int argc, char **argv)
 34 |  {
 35 |          unsigned long long num = 600851475143;
 36 |          unsigned long long max = 0;
 37 |  
 38 |          for(int i = 2 ; (i * i) <= num ; i++){
 39 |                  if (0 ==  (num % i)) {
 40 |                          if (isPrime(i)) {
 41 |                                  if (i > max) {
 42 |                                          max = i;
 43 |                                  }
 44 |                          }
 45 |                  }
 46 |          }
 47 |          printf("The largest prime factor is %llu",max);
 48 |  
 49 |          return 0;
 50 |  }
 51 |  


沒有留言: