Описание
Редицата на Трибоначи е редица, в която всеки следващ елемент се получава от сумата на предходните три елемента на редицата.
Tn = Tn-1 + Tn-2 + Tn-3
Напишете програма, която намира n-тият елемент на редицата на Трибоначи, ако са дадени първите три елемента на редицата и номерът на n-тия елемент.
Първоначално решение
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Module Tribonacci | |
Sub main() | |
Dim T1 As Integer = Integer.Parse(Console.ReadLine()) | |
Dim T2 As Integer = Integer.Parse(Console.ReadLine()) | |
Dim T3 As Integer = Integer.Parse(Console.ReadLine()) | |
Dim N As Integer = Integer.Parse(Console.ReadLine()) | |
Dim T(N - 1) As Integer | |
T(0) = T1 | |
T(1) = T2 | |
T(2) = T3 | |
For i As Integer = 3 To N - 1 | |
T(i) = T(i - 3) + T(i - 2) + T(i - 1) | |
Next i | |
Console.WriteLine(T(N - 1)) | |
Console.ReadLine() | |
End Sub | |
End Module |
Коментар
Това решение не е добро, защото N може да е число от 1 до 15000 включително, а T1, T2 и T3 – числа от -2000000 до 2000000. В решението масивът T се запълва с всички елементи на редицата.
Ново решение
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Module Tribonacci | |
Sub main() | |
Dim T1 As Integer = Integer.Parse(Console.ReadLine()) | |
Dim T2 As Integer = Integer.Parse(Console.ReadLine()) | |
Dim T3 As Integer = Integer.Parse(Console.ReadLine()) | |
Dim N As Integer = Integer.Parse(Console.ReadLine()) | |
Dim i As Integer = 4 | |
Dim nextMember As Integer = 0 | |
While i <= N | |
nextMember = T1 + T2 + T3 | |
T1 = T2 | |
T2 = T3 | |
T3 = nextMember | |
i += 1 | |
End While | |
Console.WriteLine(nextMember) | |
Console.ReadLine() | |
End Sub | |
End Module |
Коментар
В това решение последните три члена на редицата се пазят в променливите T1, T2 и Т3. Масиви не се използват.