본문 바로가기
개발/C#

유니티 C# 소인수 분해 코드 간단 구현 Prime factorization

by SPNK 2023. 10. 27.
반응형
  • 코드 작성
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

public class PrimeDecomposition : MonoBehaviour
{
    // 수의 소인수를 찾는 함수
    public static List<int> PrimeFactors(int n)
    {
        List<int> factors = new List<int>();
        
        // 홀수가 될 때까지 숫자를 2로 나누기
        while (n % 2 == 0)
        {
            factors.Add(2);
            n /= 2;
        }

        // n은 이 점에서 홀수여야 하므로 2(i = i + 2)의 스킵할 수 있음
        for (int i = 3; i <= Mathf.Sqrt(n); i += 2)
        {
            while (n % i == 0)
            {
                factors.Add(i);
                n /= i;
            }
        }

        // n이 여전히 1보다 크면 소수
        if (n > 1)
            factors.Add(n);

        return factors;
    }

    void Start()
    {
        int numberToDecompose = 56; // 분해할 수 지정
        List<int> primeFactors = PrimeFactors(numberToDecompose);

        Debug.Log(분해할숫자 + "의 소인수: " + string.Join(", ", 소인수목록));
    }
}
반응형

댓글