5. 計算次方及餘數

namespace Q5
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var a = int.Parse(textBox1.Text);
            var b = int.Parse(textBox2.Text);
            var c = int.Parse(textBox3.Text);

            long s = 1;
            for (int i = (int)Math.Ceiling(Math.Log2(b)); i >= 0; i--)
            {
                s = s * s % c;
                if ((b >> i) % 2 == 1)
                {
                    s = a * s % c;
                }
            }
            textBox4.Text = s.ToString();
        }
    }
}

Last updated