C++自守数的运算不是程序的错误
/*自守数 如果某个数的平方的末尾几位数等于这个数,那么就称这个数为自守数。*/
int 自守数(0), 数的平方(0), 判(1), 个数(0);
while (自守数++ < 10000)
{
个数 = 自守数;
数的平方 = 自守数 * 自守数;
判 = 1;
do
{
if (数的平方 % 10 != 个数 % 10)
{ 判 = 0; break; }
数的平方 /= 10;
} while (个数 /= 10);
if (判) std::cout << 自守数 << " ";
}
int 数 = 0, 个数 = 0, 数的平方 = 0; bool 判 = true;
while (++数 < 10000)
{
个数 = 数; 数的平方 = 数 * 数; 判 = true;
do
{
if (数的平方 % 10 != 个数 % 10)
{ 判 = false; break; }
数的平方 /= 10;
} while ((个数 /= 10) > 0);
if (判) { Console.Write("自守数:{0}", 数); Console.WriteLine(" {0}", 数 * 数); }
};
// C++.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <atltime.h>
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
/*自守数 如果某个数的平方的末尾几位数等于这个数,那么就称这个数为自守数。*/
unsigned long int 自守数(-1), 数的平方(0), 判(1), 个数(0);
while (自守数++ < 18446744073709551615)
{
个数 = 自守数;
数的平方 = 自守数 * 自守数;
判 = 1;
do
{
if (数的平方 % 10 != 个数 % 10)
{
判 = 0; break;
}
数的平方 /= 10;
} while (个数 /= 10);
if (判)
std::cout << 自守数 << " " << 自守数 * 自守数 << endl;
}
//unsigned int length;
//cin >> length;
//int *p1 = new int[length];
//int *p2 = new int[length];
//srand((unsigned)time(NULL));
//for (int i = 0; i < length; i++)
//{
// p1[i] = rand() % 30 + 1;
// cout << p1[i] << " ";
// p2[length - 1 - i] = p1[i];
// cout << p2[length - 1 - i] << " ";
//}
//cout << endl;
//for (int q = 0; q < length; q++)
// cout << p1[q] << " ";
//cout << endl;
//for (int n = 0; n < length; n++)
// cout << p2[n] << " ";
return 0;
}
程序运算的逻辑没错误,添加数被截断的判断:
#include "stdafx.h"
#include <stdlib.h>
#include <windows.h>
#include <atltime.h>
#include <iostream>
#include <list>
#include <fstream>
#include <string>
#include <sstream>
#include<bitset>
using namespace std;
using std::bitset;
/*自守数 如果某个数的平方的末尾几位数等于这个数,那么就称这个数为自守数。#include <sstream>*/
unsigned long long 自守数(0), 数的平方(0), 个数(0); int 判(1), 断(0);
while (1)
{
个数 = 自守数; 断 = pow(自守数 % 10, 2);
数的平方 = pow(自守数, 2);
if (数的平方 % 10 != 断 % 10)
{
std::cout << 自守数 << "自守数 数的平方" << 数的平方 << "平方数被截断" << 断 << endl;
break;
}
判 = 1;
do
{
if (数的平方 % 10 != 个数 % 10)
{
判 = 0; break;
}
数的平方 /= 10;
} while (个数 /= 10);
if (判)
std::cout << 自守数 << " " << 自守数 * 自守数 << endl;
自守数++;
}
system("pause");
2021-10-28:
bool 自守数新解(int n)
{
return (n * n - n) %
(n < 10 ? 10 :
n < 100 ? 100 :
n < 1000 ? 1000 :
n < 10000 ? 10000 :
n < 100000 ? 100000 :
n < 1000000 ? 1000000 :
n < 10000000 ? 10000000 :
n < 100000000 ? 100000000 :
n < 1000000000 ? 1000000000 :
n < 10000000000 ? 10000000000 :
1);
}
bool 自守数新解(int n)
{
int a = n, b = 10;
while ((a/=10))b *= 10;
return (n * n - n) % b;
}