[HDU] [2028] Lowest Common Multiple Plus

Problem Description

Loading...

Problem Analysis

Code I wrote on November 8th… And then this problem showed up in this week’s practice… -_-|| Anyway…let’s review it once more~ The least common multiple of several numbers This approach is to find the largest number Then keep adding +1+1+1+1+1 And then find a number that every number divides evenly I originally thought it would TLE…but it didn’t…

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<stdio.h>
int main()
{
    int i,n,s[500],m;
    while(scanf("%d",&n)!=EOF)
    {
        m=0;
        for(i=0;i<n;i++)
        {
            scanf("%d",&s[i]);
            if(m<s[i])  m=s[i];
        }
        for(i=0;i<n;i++)
        {
          if(m%s[i]!=0)
          {
              m++;
              i=-1;
          }
        }
        printf("%d\n",m);

    }
    return 0;

}

Let’s learn this way of finding the LCM of several numbers This method really is crude, feels bad I’ll come back and add it once I learn the others

20160403 addendum:

After computing the LCM of the first two numbers, compute the LCM of that with the next one Loop this operation, and the final result is the LCM of them all

Note that because multiplying first and then dividing may overflow with int you need to divide first and then multiply

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include<stdio.h>
int gcd(int a,int b) {
    if(b==0)
        return a;
    else
        return gcd(b,a%b);
}
int main() {
    int n;
    while(scanf("%d",&n)!=EOF) {
        int t;
        scanf("%d",&t);
        for(int i=1; i<n; i++) {
            int t2;
            scanf("%d",&t2);
            t=t/gcd(t,t2)*t2;
        }
        printf("%d\n",t);
    }
    return 0;
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...