C language to calculate the least common multiple of two numbers

藏色散人
Release: 2020-09-14 09:54:14
Original
40920 people have browsed it

The method of calculating the least common multiple of two numbers in C language: list the multiples of the two numbers, compare them one by one, and find the same multiple, that is, the common multiple. The code is [while(1) {if(max%a==0&&max%b==0){lcm=max;break;}】.

C language to calculate the least common multiple of two numbers

LCM (Least Common Multiple) is the least common multiple. The least common multiple of two values ​​is the smallest positive value that is a common multiple of two values.

For example, the multiple of 3 and 4 is 12:

3 →3,6,9,12,15 ...
4 →4,8,12,16,20 ...
Copy after login

The minimum multiple of both is 12, so the least common multiple of 3 and 4 is 12.

The implementation code of this algorithm is as follows:

#include<stdio.h>int main() {
   int a, b, max, step, lcm;

   a   = 3;
   b   = 4;
   lcm = 0;

   if(a > b)
      max = step = a;
   else
      max = step = b;

   while(1) {
      if(max%a == 0 && max%b == 0) {
         lcm = max;
         break;    
      }

      max += step;
   }

   printf("LCM is %d", lcm);
   return 0;}
Copy after login

Output:

LCM is 12
Copy after login

Recommended related video tutorials: "Python Tutorial", "C Video Tutorial

This article is about the method of calculating the least common multiple of two numbers in C. I hope it will be helpful to friends in need!

The above is the detailed content of C language to calculate the least common multiple of two numbers. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template