Project Euler: Solution for Problem 5

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 }

 

转载于:https://www.cnblogs.com/QianL/p/5656872.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值