码迷,mamicode.com
首页 > 其他好文 > 详细

Project Euler: Solution for Problem 5

时间:2016-07-10 00:54:01      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

Smallest multiple

Problem 5

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?

 

Source link: https://projecteuler.net/problem=5 

 

Solution: implemented in C++.

This problem could be simplified to two question: 

  1. All prime number cannot be divide, thus we could mutiple all prime numbers first.
  2. Based on the prouction of prime numbers we got, we can calculate the lowest common multiple number of composite numbers and production we already have, if only the production result is not evenly divisible by the composite number.

 

 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 #include<cmath>
 5 using namespace std;
 6     
 7 int fac(int origin, int comps, vector<int> prs);
 8 
 9 void main()
10 {
11     const int num = 20;  
12     int pr_product = 1;  //the result stores in this varaiable
13     vector<int> pr;  //vector containing all prime numbers in range (0,20)
14     vector<int> compo;  //vector containing all composite numbers in range (0,20)
15     //find out all prime numbers among 1-20
16     for(int i = 2; i < (num + 1); i++){
17         bool isPr = true;
18         for(int cnt = 2; cnt < i; cnt++){
19             if( i%cnt == 0){
20                 isPr = false;
21                 break;
22             }
23         }
24         if(isPr){  //prime numbers push into vector pr
25             pr_product *= i;
26             pr.push_back(i);
27         }else{    //composite numbers push into vector compo
28             compo.push_back(i);
29         }
30     }
31     for(int i = 0; i < compo.size(); i++){  //For each composite number which the result we have now cannot divide
32         if(pr_product%compo[i] != 0)      //determine lowest common multiple
33             pr_product = fac(pr_product, compo[i], pr);
34     }
35     cout<<pr_product<<endl;
36 }
37 
38 int fac(int origin, int comps, vector<int> prs){  //determine lowest common multiple
39     int record = 1;
40     for(int i = 0; comps > prs[i]; i++){
41         while( (origin%prs[i] == 0) && (comps%prs[i] == 0) ){
42             record *= prs[i];
43             origin /= prs[i];
44             comps /= prs[i];
45         }
46     }
47     return record = origin * comps * record;
48 }

 

Project Euler: Solution for Problem 5

标签:

原文地址:http://www.cnblogs.com/QianL/p/5656872.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!