ProjectEuler_P5

Question:

 

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

 

解题思路:

考虑在20范围内的素数出现的最大阶数!

如10以内的smallest number that can be divided

10 = 2^1*5^1

9=3^2

8=2^3

7=7^1

6=2^1*3^1

5=5^1

4=2^2

3=3^1

2=2^1

所以:

number = 2^3*3^2*5^1*7^1 = 2520

同理可求出20以内的smallest number that can be divided

 

C Code:

#include <stdio.h>

int IsPrim(int n)
{
  int i;
  for(i = 2;i*i <= n;i++)
  {
    if(0 == n%i)
      return 0;
  }
  return 1;
}

void main()
{
  int prim[20] = {0};
  int primMulNum[20] = {0};
  int primCount = 1;
  int i = 0;
  long smallestRes = 1;
  prim[0] = 2;
  for(i = 3;i < 20;i++)
  {
    if(IsPrim(i))
    {
      prim[primCount++] = i;
    }
  }
  for(i = 1;i < 20;i++)
  {
    int j = 0;
    for(j = 0;i >= prim[j] && j < primCount;j++)
    {
      int count = 0;
      int temp = i;
      while(0 == temp % prim[j])
      {
        count++;
        temp = temp/prim[j];
      }
      if(count > primMulNum[j])
      {
        primMulNum[j] = count;
      }
    }
  }
  for(i = 0;i < primCount;i++)
  {
    int count = primMulNum[i];
    while(count > 0)
    {
      smallestRes *= prim[i];
      count--;
    }
  }
  printf("%ld\n",smallestRes);
}

 

Answer:

232792560

posted on 2014-04-23 19:29  楠哥1991  阅读(147)  评论(0编辑  收藏  举报

导航