>  기사  >  백엔드 개발  >  강력한 숫자를 확인하는 C 프로그램

강력한 숫자를 확인하는 C 프로그램

WBOY
WBOY앞으로
2023-09-07 09:09:12955검색

강력한 숫자를 확인하는 C 프로그램

숫자 'n'이 주어지면 주어진 숫자가 강한 숫자인지 확인해야 합니다.

강한 숫자는 모든 숫자의 계승값의 합이 숫자 'n'과 같은 숫자입니다. 계승은 해당 숫자를 포함하여 해당 숫자보다 작은 모든 숫자를 곱한 결과이며 !(느낌표)로 표시됩니다. 예: 4! = 4x3x2x1 = 24.

따라서 숫자가 강한지 확인하려면 숫자의 각 비트를 추출해야 합니다. 예를 들어 숫자가 145인 경우 1, 4, 5를 추출한 다음 각 숫자인 1의 계승을 계산합니다. ! = 1, 4! = 24,5! =120.

이제 1 + 24 + 120을 더하면 145가 되는데, 이는 주어진 입력과 정확히 동일하므로 이 숫자가 강력하다고 말할 수 있습니다.

Example

Input: n = 124
Output: No it is not a strong number
Explanation: 1! + 2! + 4! = 27 which is not equal to n i.e, 124
Input: n = 145
Output: Yes it is a strong number
Explanation: 1! + 4! + 5! = 145

문제를 해결하기 위해 아래에서 사용한 방법은 다음과 같습니다

우리는 −

  • 한 자리부터 시작하는 각 숫자를 취하여 팩토리얼을 구하겠습니다.
  • 우리는 이 숫자의 계승을 추가합니다.
  • 결과를 원래 숫자와 비교하세요. 같으면 그 숫자는 강한 숫자이고, 그렇지 않으면 그 숫자는 강한 숫자가 아닙니다.

Algorithm

START
In Function int factorial(int r)
   Step1 -> Initialize int fact and set as 1
   Step2-> Loop while r>1
      Set fact as fact * r
      Decremnet r by 1
   End Loop
   Step 3-> Return fact
   End Function factorial
In Function int check(int n)
   Step 1-> Initialize int temp, rem and result, set result as 0
   Step 2-> Set temp as n
   Step 3-> Loop while temp
      Set rem as temp % 10
      Set result as result + factorial(rem)
      Set temp as temp/10
   End loop
   Step 4-> If result == n then,
      Return 1
   Step 5-> Else
   Return 0
   End function check
In main(int argc, char const *argv[])
   Step 1-> Initialise and set n as 145
   Step 2->If check(n) is valid then,
      Print "Yes it is a strong number”
   Step 3-> Else
      Print "no it is not a strong number”
STOP

Example

Live Demonstration

#include <stdio.h>
int factorial(int r) {
   int fact = 1;
   while(r>1) {
      fact = fact * r;
      r--;
   }
   return fact;
}
int check(int n) {
   int temp, rem, result = 0;
   temp = n;
   while(temp) {
      rem = temp % 10;
      result = result + factorial(rem);
      temp = temp/10;
   }
   if (result == n)
      return 1;
   else
      return 0;
}
int main(int argc, char const *argv[]) {
   int n = 145;
   if (check(n))
      printf("Yes it is a strong number</p><p>");
   else
      printf("no it is not a strong number</p><p>");
   return 0;
}

위 코드를 실행하면 다음과 같은 출력이 생성됩니다 −

Yes it is a strong number

위 내용은 강력한 숫자를 확인하는 C 프로그램의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제