给定两个数字,开始和结束代表一个范围。目标是找到在[开始,结束]之间存在的一元数的计数。
我们可以通过以下步骤检查数字是否为一元:如果我们采用数字13,则12 + 32 = 10,则12 + 02 = 1因此,这种方式的最终和为1,因此13是一元。
例如
start=1 end=20输出结果
范围内的一元数计数为: 5
The numbers are : 1, 7, 10, 12, and 13
start=50 end=100输出结果
范围内的一元数计数为: 7
The numbers are − 59, 63, 67, 74, 75, 78, and 89
以下程序中使用的方法如下-
在1到9之间的数字1和7是一元的。对于其他数字,我们将使用数字平方和,直到得到1。继续对范围内的所有数字进行此过程。以这种方式找到的所有一元数的增量计数。
以两个整数开头,结尾作为输入。
功能 check_unary(int number) 如果传递的值是一元,则返回true,否则返回false。
功能 Unary_range(int start, int end) 接受范围变量并返回该范围内的一元数计数。
将初始计数设为0。使用for循环,从i = start到end遍历。如果check_unary(i) 返回true,然后增加计数。
内 check_unary(int number),进行临时变量计数。
如果数字N为1、7,则返回true。对于所有其他小于10的数字,返回false(number / 10 == 0)。
然后在while循环中计算数字的平方和。
再打一次 check_unary(int number) 对于这样的连续和,直到和成为1。
返回计数作为结果。
#include <iostream>
using namespace std;
bool check_unary(int number){
int total;
if (number == 1 ){
return true;
}
else if(number == 7){
return true;
}
else if (number / 10 == 0){
return false;
}
while (number!= 0){
int temp = number % 10;
total = total + temp * temp;
number = number / 10;
}
check_unary(total);
}
int Unary_range(int start, int end){
int count = 0;
for (int i = start; i <= end; i++){
if (check_unary(i) == 1){
count++;
}
}
return count;
}
int main(){
int start = 200, end = 400;
cout<<"范围内的一元数计数为: "<<Unary_range(start, end);
return 0;
}输出结果如果我们运行上面的代码,它将生成以下输出-
范围内的一元数计数为: 31