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

โปรแกรม Java คำนวณผลรวมจำนวนธรรมชาติ (Sum of Natural Numbers)

ในบทความนี้ เราจะเรียนรู้วิธีคำนวณผลรวมของจำนวนธรรมชาติในช่วงที่กำหนดในภาษา Java จำนวนธรรมชาติคือจำนวนเต็มบวก 1, 2, 3, ... ไปเรื่อยๆ

ตัวอย่างการทำงาน

อินพุต:

50 and 100

เอาต์พุต:

Sum of natural numbers from 50 to 100 is 3825

อัลกอริทึม

  1. เริ่มต้นโปรแกรม
  2. ประกาศตัวแปร: my_lower_limit, my_upper_limit, sum
  3. รับค่าตัวเลขเริ่มต้นและสิ้นสุดจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
  4. ใช้ลูป for บวกเลขทุกตัวตั้งแต่ lower_limit ถึง upper_limit
  5. แสดงผลลัพธ์
  6. จบโปรแกรม

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

import java.util.Scanner;

public class NaturalNumbersSum {
    public static void main(String[] args) {
        int my_lower_limit, my_upper_limit, sum = 0;

        System.out.println("Required packages have been imported");
        Scanner scanner = new Scanner(System.in);
        System.out.println("A scanner object has been defined");

        System.out.print("Enter the starting number: ");
        my_lower_limit = scanner.nextInt();
        System.out.print("Enter the max number: ");
        my_upper_limit = scanner.nextInt();

        for (int i = my_lower_limit; i <= my_upper_limit; ++i) {
            sum += i;
        }

        System.out.println("The sum of natural numbers from " + my_lower_limit +
                " to " + my_upper_limit + " is " + sum);
    }
}

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

public class NaturalNumbersSum {
    public static void main(String[] args) {
        int my_input_1 = 50, my_input_2 = 100, sum = 0;

        System.out.println("The first and last numbers are defined as " + my_input_1 + " and " + my_input_2);

        for (int i = my_input_1; i <= my_input_2; ++i) {
            sum += i;
        }

        System.out.println("The sum of natural numbers from " + my_input_1 +
                " to " + my_input_2 + " is " + sum);
    }
}

สูตรทางคณิตศาสตร์ (เร็วกว่าลูป)

สำหรับช่วงใหญ่ๆ สามารถใช้สูตร: Sum = n/2 × (first + last)

long n = (long) my_upper_limit - my_lower_limit + 1;
long sum = n * (my_lower_limit + my_upper_limit) / 2;

วิธีนี้มีความซับซ้อน O(1) เร็วกว่าลูป O(n) มากสำหรับช่วงขนาดใหญ่