Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 계승의 자릿수 계산

<시간/>

정수 값이 주어지고 작업은 먼저 숫자의 계승을 계산한 다음 결과의 총 자릿수를 계산하는 것입니다.

공장수란 무엇입니까

숫자의 계승은 숫자의 값을 1로 감소시키면서 숫자의 숫자를 곱하여 계산됩니다. 기호 '!'로 표시됩니다. 즉, 0!, 1!, 2!, 3!, 5!,... .,등. 팩토리얼 0! 그리고 1! 항상 1입니다.

I.e. factorial of 2 = 2 * (2-1) = 2 * 1 = 2
      factorial of 3 = 3 * (3-1) * (2-1) = 3 * 2 * 1 = 6

Input − factorial(6)
Output − number of digits in factorial(6) is: 3

설명 - 6의 계승값은 720이고 3자리를 포함하므로 결과는 3입니다.

Input − factorial(12)
Output− number of digits in factorial(12) is: 9

설명 - 12의 계승값은 479001600이고 9자리를 포함하므로 결과는 9입니다.

아래 프로그램에서 사용된 접근 방식은 다음과 같습니다.

  • 팩토리얼을 계산해야 하는 개수를 입력하세요.

  • 숫자가 0보다 작으면 음수에는 계승 값이 없으므로 0을 반환합니다.

  • 숫자가 1이면 1이기 때문에 1을 반환합니다! 1이고 1자리입니다.

  • 숫자가 1보다 크면 즉 2 이상으로 시작하면 2에서 시작하여 숫자보다 작거나 같을 때까지 하나의 루프를 만듭니다.

  • 하나의 임시 변수를 d라고 가정하고 루프 외부에서 0으로 초기화하고 루프 내부에서 i가 반복될 때까지 log10(i) 값으로 계속 추가합니다.

  • 그 후 'floor(d)+1'의 하한값을 반환합니다.

  • 결과를 인쇄하십시오.

예시

#include <iostream>
#include <cmath>
using namespace std;
// This function returns the number of digits present in num!
int count_digits(int num){
   // factorial exists only if num <= 0
   if (num < 0){
      return 0;
   }
   // base case
   if (num <= 1){
      return 1;
   }
   // else iterate through num and calculate the
   // value
   double d = 0;
   for (int i=2; i<=num; i++){
      d += log10(i);
   }
   return floor(d) + 1;
}
int main(){
   cout<<"number of digits in factorial(1) is: "<<count_digits(1)<< endl;
   cout<<"number of digits in factorial(6) is: "<<count_digits(6) << endl;
   cout<<"number of digits in factorial(106) is: "<<count_digits(106) << endl;
   return 0;
}

출력

위의 코드를 실행하면 다음 출력이 생성됩니다 -

number of digits in factorial(1) is: 1
number of digits in factorial(6) is: 3
number of digits in factorial(106) is: 171