要求编写函数 selfhold,判断一个数是否是一个自守数,若是,则返回 1,否则返回 0。
时间: 2024-05-15 07:20:00 浏览: 11
自守数(也称自反数或不变数)是指一个数的平方的末位数字等于该数本身。例如,5的平方是25,5是自守数。
以下是 Python 代码实现:
```python
def selfhold(n):
square = n * n
while n > 0:
if n % 10 != square % 10:
return 0
n //= 10
square //= 10
return 1
```
函数首先计算出传入参数的平方,然后依次比较传入参数和平方的每一位数字,如果有不相等的,就返回0,否则返回1。
相关问题
求 200000 以内的自守数。要求编写函数 selfhold,判断一个数是否是一个自守数,若是,则返回 1,否则返回 0。
一个数如果是自守数,那么它的平方的末尾几位数应该等于它本身的末尾几位数。例如,5是自守数,因为5的平方是25,末尾数等于5本身。因此,我们可以使用以下的selfhold函数来判断一个数是否是自守数:
```c++
int selfhold(int n){
int square = n * n;
int divisor = 10;
while(n >= divisor){
if(square % divisor == n) return 1;
divisor *= 10;
}
return (square % divisor == n) ? 1 : 0;
}
```
然后,我们可以编写一个程序来输出200000以内的自守数:
```c++
#include <iostream>
using namespace std;
int selfhold(int n){
int square = n * n;
int divisor = 10;
while(n >= divisor){
if(square % divisor == n) return 1;
divisor *= 10;
}
return (square % divisor == n) ? 1 : 0;
}
int main(){
int count = 0;
for(int i = 0; i <= 200000; i++){
if(selfhold(i)){
count++;
cout << i << " ";
}
}
cout << endl << "Total count: " << count << endl;
return 0;
}
```
以上程序会输出200000以内的自守数,并统计自守数的个数。
/*-------------------------------------------------- 注意:部分源程序给出如下。请勿改动主函数main和其它 函数中的任何内容,仅在函数的花括号中填入所编 写的若干语句。 -------------------------------------------------------*/ #include <iostream> using namespace std; int selfhold(long number); int main() { long number; for(number=0;number<200000;number++) { if(selfhold(number)==1) { cout<<number<<endl; } } return 0; } int selfhold(long number) /*判断数number是否是一个自守数*/ { /**********Program**********/ char a[10]=number; int chang=strlen(a); int cheng=number*number; char b[100]=cheng; int ch=strlen(b);int sum=0; for(int i=0;i<chang;i++){ if(a[i]==b[ch-chang])sum++; } if (sum==chang)return 1; else return 0; } /**********Program**********/
int selfhold(long number) /*判断数number是否是一个自守数*/ {
char a[10];
sprintf(a,"%ld",number);
int chang=strlen(a);
long cheng=number*number;
char b[100];
sprintf(b,"%ld",cheng);
int ch=strlen(b);
int sum=0;
for(int i=0;i<chang;i++){
if(a[i]==b[ch-chang+i])
sum++;
}
if (sum==chang)
return 1;
else
return 0;
}