簡體   English   中英

指數的最后一位數字-錯誤答案-C#

[英]Last digit in an exponent - wrong answer - C#

我正在嘗試解決此問題: http : //www.spoj.com/problems/LASTDIG/ ,它需要一個底數和指數,我必須輸出取冪結果的最后一位,但是在線法官說我的程序雖然給出了錯誤的答案,但是對於典型的測試用例,我的輸出是正確的。

注意:我必須使用快速模冪運算,對此有一個很好的解釋: https : //www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/fast-modular-exponentiation

using System;

public class Test
{
    public static void Main()
    {
        int val = Convert.ToInt32(Console.ReadLine());
        for (int i=0; i<val; i++ )
        {
            string input = Console.ReadLine();
            int a = Convert.ToInt32(input.Split()[0]);
            int b = Convert.ToInt32(input.Split()[1]);
            if (a==0)
            {
                Console.WriteLine(0);
            } else if(b==0)
            {
                Console.WriteLine(1);
            } else {
                a=a%10;
                string bToBinary=Convert.ToString(b, 2);
                double temp = 1;
                for(int j=bToBinary.Length-1, k=0; j>=0; j--, k++)
                {
                    if (bToBinary[j] == '1')
                    {
                        temp = temp*(Math.Pow(a, Math.Pow(2, k)));
                    }
                }
                Console.WriteLine(temp%10);
            }
        }
    }
}

輸入樣例:

4
3 10
6 2
14 11
1 0

該程序的輸出:

9
6
4
1

每個功率以1、2或4重復。

這是寫出的圖案

1 = {1,1,1,1}
2 = {2,4,8,6}
3 = {3,9,7,1}
4 = {4,6,4,6}
5 = {5,5,5,5}
6 = {6,6,6,6}
7 = {7,9,3,1}
8 = {8,4,2,6}
9 = {9,1,9,1}

如您所知,具有相同單位的冪的模式,例如13的模式與3的模式相同

因此,您應該能夠像這樣編寫程序

public class Test
{
    public static void Main()
    {
        int val = Convert.ToInt32(Console.ReadLine());
        for (int i=0; i<val; i++ )
        {
            string input = Console.ReadLine();
            int a = Convert.ToInt32(input.Split()[0]);
            int b = Convert.ToInt32(input.Split()[1]);
            if (a==0)
            {
                Console.WriteLine(0);
            } else if(b==0)
            {
                Console.WriteLine(1);
            } else {
               Console.WriteLine (Math.Pow(a%10,b%4 + 4) %10);  
            }
        }
    }
}

您不應強求解決方案。 問題專門要求結果的最后一位數字 ,而不是全部。

乘法中應該有某種可以濫用的模式。 讓我們暫時將功率0降低,因為這是一種特殊的情況。 例如,我們知道任何正整數的10或20的冪將以0結尾,而5始終以5結尾。我們可以濫用此模式,因為無論我們提高多少次,最后一位總是處於這種模式內。

可以這樣提取模式:

IEnumerable<int> FindExpLastDigitPattern(int i)
{
    var result = 1;

    var list = new List<int>();
    while (!list.Contains(result = (result * i) % 10))
    {
        list.Add(result);
        yield return result;
    }
}

而且我們還可以基於冪(即index = (power - 1) % pattern.Count預測此模式中的位置。

考慮到這一點,我們可以計算出冪的最后一位:

int ComputeLastDigitOfExponentiation(int i, int power)
{
    // arguments guard...

    // handles specific case
    if (power == 0)  return 1;

    var pattern = FindExpLastDigitPattern(i).ToList();

    return pattern[(power - 1) % pattern.Count];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM