Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java หาผลคูณ 2 เลขด้วย Recursion


ในบทความนี้ เราจะทำความเข้าใจวิธี หาผลคูณของ 2 เลขด้วยการเรียกซ้ำ (Recursion) โดยไม่ใช้ตัวดำเนินการ * โดยตรง

หลักการ: a × b = a + a + ... + a (บวก a ทั้งหมด b ครั้ง) หรือใช้หลักการลดปัญหาลงมาเป็นกรณีพื้นฐาน

ตัวอย่าง Input และ Output

Input:

Enter two number : 12 and 9

Output:

The product of 12 and 9 is 108

อัลกอริธึม

ขั้นตอนที่ 1 - เริ่มต้น
ขั้นตอนที่ 2 - ประกาศตัวแปร my_input_1, my_input_2
ขั้นตอนที่ 3 - อ่านค่าจากผู้ใช้ หรือกำหนดค่าเริ่มต้น
ขั้นตอนที่ 4 - สร้างฟังก์ชัน getproduct แบบ recursive รับ 2 ตัวเลข คืนค่าผลคูณ
ขั้นตอนที่ 5 - เรียกฟังก์ชันและแสดงผล
ขั้นตอนที่ 6 - หยุด

ตัวอย่างที่ 1: รับค่าจากผู้ใช้

import java.util.Scanner;
public class ProductRecursion {
    public static void main(String[] args) {
        int my_input_1, my_input_2;
        System.out.println("Required packages have been imported");
        Scanner my_scanner = new Scanner(System.in);
        System.out.println("A reader object has been defined");
        System.out.print("Enter the number : ");
        my_input_1 = my_scanner.nextInt();
        System.out.print("Enter the number : ");
        my_input_2 = my_scanner.nextInt();
        System.out.println("The product of " + my_input_1 + " and " + my_input_2 + " is " + getproduct(my_input_1, my_input_2));
    }
    static int getproduct(int my_input_1, int my_input_2) {
        if (my_input_1 < my_input_2)
            return getproduct(my_input_2, my_input_1);
        else if (my_input_2 != 0)
            return (my_input_1 + getproduct(my_input_1, my_input_2 - 1));
        else
            return 0;
    }
}

Output

Required packages have been imported
A reader object has been defined
Enter the number : 12
Enter the number : 9
The product of 12 and 9 is 108

ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า

public class ProductRecursion {
    public static void main(String[] args) {
        int my_input_1, my_input_2;
        my_input_1 = 12;
        my_input_2 = 9;
        System.out.println("The two numbers are defined as " + my_input_1 + " and " + my_input_2);
        System.out.println("The product of " + my_input_1 + " and " + my_input_2 + " is " + getproduct(my_input_1, my_input_2));
    }
    static int getproduct(int my_input_1, int my_input_2) {
        if (my_input_1 < my_input_2)
            return getproduct(my_input_2, my_input_1);
        else if (my_input_2 != 0)
            return (my_input_1 + getproduct(my_input_1, my_input_2 - 1));
        else
            return 0;
    }
}

Output

The two numbers are defined as 12 and 9
The product of 12 and 9 is 108