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

โปรแกรม C# แสดงตัวประกอบของเลข

ตัวประกอบ (Factors) ของเลข n คือเลขที่หาร n ลงตัว (เศษ 0)

อัลกอริทึม

  1. รับค่า n จากผู้ใช้
  2. วนลูป i จาก 1 ถึง n
  3. ถ้า n % i == 0 แสดงว่า i เป็นตัวประกอบ

ตัวอย่างโค้ดเต็ม

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
    class ApplicationOne {
        static void Main(string[] args) {
            int n, i;
            Console.WriteLine("Enter the Number:");
            n = int.Parse(Console.ReadLine());
            Console.WriteLine("Factors:");
            for (i = 1; i <= n; i++) {
                if (n % i == 0) {
                    Console.WriteLine(i);
                }
            }
            Console.ReadLine();
        }
    }
}

ตัวอย่าง: ใส่ 12 → ได้ 1, 2, 3, 4, 6, 12

การเพิ่มประสิทธิภาพ: วนแค่ถึง √n แล้วนำคู่ตัวประกอบมารวม จะเร็วกว่าสำหรับเลขใหญ่