首页 > 文章列表 > 在C++中的可重构数

在C++中的可重构数

关键词:C语言 可重构
276 2023-08-19

给定一个整数类型的值,假设为number。任务是检查给定的数字是否可重构。如果是,打印该数字是可重构数字,否则打印不可能。

什么是可重构数字?

当一个数字可以被其可用因子的总数整除时,它就是可重构的。例如,数字9是可重构的,因为它有3个因子(1、3、9),而9可以被3整除,因此它是一个可重构数字。

让我们看看这个的各种输入输出情况-

输入 - int number = 9

输出 - 这是一个可重构数字

解释 - 当一个数字可以被其可用因子的总数整除时,它就是可重构的。我们给定了一个数字9,它是可重构的,因为它有3个因子(1、3、9)

and 9 is divisible by 3 hence its a refactorable number.

Input − int number = 10

Output − It isn't a Refactorable number

Explanation − A number is refactorable when it is divisible by its total count of factors available. We are given a number 10, which isn't refactorable as it has a total number of factors i.e. 4(1, 2, 5, 10) and 10 isn’t divisible by 4 hence it is not a refactorable number

Approach used in the below program is as follows

  • Input a variable of integer type, let’s say, number.

  • Pass the data to the function check_Refactorable(int number) of the bool type.

  • Inside the function check_Refactorable(int number)

    • Declare an integer type variable as count to 0.

    • Start loop FOR from i to 1 till i is less than sqrt(number). Inside the loop, check IF number % i = 0 then check IF number / i = i then pre increment the count by 1.

    • ELSE, set the count as count + 2.

    • Return number % count == 0

  • Print the result.

Example

#include <bits/stdc++.h>
using namespace std;
bool check_Refactorable(int number){
   int count = 0;
   for (int i = 1; i <= sqrt(number); ++i){
      if(number % i==0){
         if(number / i == i){
            ++count;
         }
         else{
            count += 2;
         }
      }
   }
   return number % count == 0;
}
int main(){
   int number = 9;
   if(check_Refactorable(number) == 1){
      cout<<"It is a Refactorable number";
   }
   else{
      cout<<"It isn't a Refactorable number";
   }
   return 0;
}

Output

If we run the above code it will generate the following Output

It is a Refactorable number