DEV Community

Keerthiga P
Keerthiga P

Posted on

Ternary Operator,Prime Number,GCD

Ternary Operator for 3 numbers :

Java:

class Main {
    public static void main(String[] args) {
        int a = 10, b = 5, c = 8;

        int smallest = (a < b) 
                        ? (a < c ? a : c) 
                        : (b < c ? b : c);

        System.out.println(smallest);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Javascript:

let a = 10, b = 55, c = 80;
let smallest = (a < b) 
                ? (a < c ? a : c) 
                : (b < c ? b : c);

console.log(smallest);
Enter fullscreen mode Exit fullscreen mode

Output:

Python:

a = 100
b = 53
c = 18
smallest = a if (a < b and a < c) else (b if b < c else c)
print(smallest)
Enter fullscreen mode Exit fullscreen mode

Output:

Range of prime numbers :

FlowChart:

Python:

no1 = 10
while no1 <= 50:
    div = 2
    flag = True
    while div <= no1 // 2:
        if no1 % div == 0:
            flag = False
            break
        div = div + 1
    if flag:
        print(no1, "is prime")
    no1 = no1 + 1
Enter fullscreen mode Exit fullscreen mode

Output:

JavaScript:

let no1 = 10;
while (no1 <= 50) {
    let div = 2;
    let flag = true;
    while (div * div <= no1) {
        if (no1 % div === 0) {
            flag = false;
            break;
        }
        div++;
    }
    if (flag && no1 > 1) {
        console.log(no1 + " is prime");
    } 
    no1++;
}
Enter fullscreen mode Exit fullscreen mode

Output:

Java:

public class PrimeCheck {
    public static void main(String[] args) {
        int no1 = 10;
        while (no1 <= 50) {
            int div = 2;
            boolean flag = true;
            while (div * div <= no1) {
                if (no1 % div == 0) {
                    flag = false;
                    break;
                }
                div++;
            }
            if (flag && no1 > 1) {
                System.out.println(no1 + " is prime");
            } 
            no1++;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Find the Greatest of Common Divisor:

FlowChart:

python:

a = 10
b = 5
c = 8
small = a if a < b and a < c else (b if b < c else c)
print("Smallest =", small)

Enter fullscreen mode Exit fullscreen mode

Output:

Javascript:

let a = 10;
let b = 5;
let c = 8;
let small = (a < b && a < c) ? a : (b < c ? b : c);
console.log("Smallest =", small);
Enter fullscreen mode Exit fullscreen mode

Java:

public class Smallest {
public static void main(String[] args) {
    int a = 10;
    int b = 5;
    int c = 8;
    int small = (a < b && a < c) ? a : (b < c ? b : c);
    System.out.println("Smallest = " + small);
}
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)