Home  >  Article  >  Backend Development  >  C language to calculate the least common multiple of two numbers

C language to calculate the least common multiple of two numbers

藏色散人
藏色散人Original
2019-03-04 15:30:1340919browse

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 ...

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;}

Output:

LCM is 12

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!

Statement:
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