Day 5 – Padovan Sequence

작성자

분류 ,

파도바 수열은 각 항이 이전 두 항의 합이고 각 항이 공식 P(n) = P(n-2) + P(n-3)을 따르는 수열입니다.

어디에 쓰이나요?

파도반 수열은 변의 길이가 같은 삼각형을 이용하여 나선형을 형성하는 데 사용되며, 건축 디자인이나 예술 작품에서 영감을 주는 요소로 사용됩니다.


Codes

Here’s a beautifully written example of how to implement this in C#, optimizing the performance of code

PadovanSequence.cs
using System;
using System.Numerics;
class PadovanSequence
{
    public BigInteger Calculate(int n)
    {
        if (n == 0 || n == 1 || n == 2) return 1;
        BigInteger prevPrev = 1, prev = 1, current = 1, next;
        for (int i = 3; i <= n; i++)
        {
            next = prevPrev + prev;
            prevPrev = prev;
            prev = current;
            current = next;
        }
        return current;
    }
}
C#
Program.cs
using System.Diagnostics; // for Stopwatch

Console.WriteLine("Hello, Day5!");

Console.Write("Enter a number: ");
if (int.TryParse(Console.ReadLine(), out int n) && n > 0)
{

    PadovanSequence padovan = new();

    var stopwatch = Stopwatch.StartNew();
    var result = padovan.Calculate(n);
    stopwatch.Stop();

    Console.WriteLine($"Time taken: {stopwatch.Elapsed.TotalMilliseconds} ms");
    Console.WriteLine($"The {n}th term of the Padovan Sequence is {result}");

}
else
{
    Console.WriteLine("Invalid input. Please enter a number.");
}
C#

이 코드는

  • 단순성: 코드는 필요한 작업만 수행하며 불필요한 복잡성이 없습니다.
  • 효율성: 재귀 대신 루프를 사용하여 호출 스택 오버헤드를 줄이고 BigInteger를 사용하여 큰 숫자를 처리합니다.
  • 확장성: BigInteger를 사용하면 매우 큰 시퀀스의 항도 계산할 수 있습니다.

Links

Comments

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다