DEV Community

Cover image for Basic Math Logic in Programming: Sum, Factorial, and LCM
Arul .A
Arul .A

Posted on

Basic Math Logic in Programming: Sum, Factorial, and LCM

1.Find the sum of n numbers :
flow chart:

  • In python:
sum=0
num=1
while num<=10:
    sum=sum+num
    num+=1
print("The Sum of 10 Numbers : ",sum)

Enter fullscreen mode Exit fullscreen mode

Output:

  • In Java :
public class Sum_Of_Numbers{
public static void main(String[]args){
int sum=0;
int num=1;
while(num<=10){
sum+=num;
num++;
}
System.out.println(sum);

}
}

Enter fullscreen mode Exit fullscreen mode

Output:

  • In JavaScript:
let sum = 0;
let num = 1;

while (num <= 10) {
    sum = sum + num;
    num++;
}

console.log("The Sum of 10 Numbers:", sum);

Enter fullscreen mode Exit fullscreen mode

2.Find the factorial of given number:
flow chart:

  • In python:
fact=1
num=1
while num<=5:
    fact*=num
    num+=1
print("THe Factorial Of given number",fact)

Enter fullscreen mode Exit fullscreen mode

Output:

  • In Java :
public class FactorialExample {
    public static void main(String[] args) {
        int fact = 1;
        int num = 1;

        while (num <= 5) {
            fact *= num;
            num++;
        }

        System.out.println("The Factorial of given number: " + fact);
    }
}

Enter fullscreen mode Exit fullscreen mode
  • In JavaScript:
let fact = 1;
let num = 1;

while (num <= 5) {
    fact *= num;
    num++;
}

console.log("The Factorial of given number:", fact);

Enter fullscreen mode Exit fullscreen mode

3.Find the LCM of number:

flow chart:

  • In python:
no1=3
no2=9
big=no1 if no1>no2 else no2
big2=big
while True:
    if big%no1==0 and big%no2==0:
        print("The LCM is ",big)
        break    
    big+=big2

Enter fullscreen mode Exit fullscreen mode

Output :

  • In Java :
public class LCMExample {
    public static void main(String[] args) {
        int no1 = 3;
        int no2 = 9;

        int big = (no1 > no2) ? no1 : no2;
        int big2 = big;

        while (true) {
            if (big % no1 == 0 && big % no2 == 0) {
                System.out.println("The LCM is " + big);
                break;
            }
            big += big2;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
  • In JavaScript:
let no1 = 3;
let no2 = 9;

let big = (no1 > no2) ? no1 : no2;
let big2 = big;

while (true) {
    if (big % no1 === 0 && big % no2 === 0) {
        console.log("The LCM is", big);
        break;
    }
    big += big2;
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)