c ➕➕语言寻找同构
时间: 2024-01-23 08:13:54 浏览: 32
以下是C++语言寻找同构数的代码示例:
```cpp
#include <iostream>
using namespace std;
int isIsomorphic(int x) {
int square = x * x;
int len = 1;
while (square / len) {
if (len > x) {
if (square % len == x) {
return 1;
}
}
len *= 10;
}
return 0;
}
int main() {
for (int i = 1; i < 1000; i++) {
if (isIsomorphic(i)) {
cout << i << "\t";
}
}
return 0;
}
```
该程序通过定义一个`isIsomorphic`函数来判断一个整数是否为同构数,然后在主函数中循环遍历1到999的整数,判断是否为同构数并输出。
相关问题
用c语言确定两串乱序同构
两个字符串如果是乱序同构的,意味着它们包含的字符种类及其数量是相同的,只是排列顺序不同。
下面是一个用C语言实现的函数,用于判断两个字符串是否是乱序同构:
```c
#include <stdio.h>
#include <string.h>
int isAnagram(char* s, char* t) {
int sCount[26] = {0}; // 存放s字符串中每个字符出现的次数
int tCount[26] = {0}; // 存放t字符串中每个字符出现的次数
// 统计s字符串中每个字符出现的次数
int i = 0;
while (s[i] != '\0') {
sCount[s[i] - 'a']++;
i++;
}
// 统计t字符串中每个字符出现的次数
i = 0;
while (t[i] != '\0') {
tCount[t[i] - 'a']++;
i++;
}
// 判断两个字符串中的字符种类及其数量是否相同
for (i = 0; i < 26; i++) {
if (sCount[i] != tCount[i]) {
return 0;
}
}
return 1;
}
int main() {
char s[] = "anagram";
char t[] = "nagaram";
if (isAnagram(s, t)) {
printf("两个字符串是乱序同构的\n");
} else {
printf("两个字符串不是乱序同构的\n");
}
return 0;
}
```
上面的代码中,我们使用两个数组`sCount`和`tCount`来分别统计两个字符串中每个字符出现的次数。最后再比较这两个数组,如果它们的值完全相同,就说明这两个字符串是乱序同构的。
用c语言写一个输出同构数的程序
同构数是指一个数的平方的各个位上的数字排列顺序可以组成它本身,例如:25的平方是625,可以发现25的平方的各个位上的数字排列顺序可以组成25本身,因此25就是一个同构数。
下面是一个输出同构数的程序:
```c
#include <stdio.h>
int isIsomorphic(int n) {
int square = n * n;
int count1[10] = {0}, count2[10] = {0};
while (n > 0) {
count1[n % 10]++;
n /= 10;
}
while (square > 0) {
count2[square % 10]++;
square /= 10;
}
for (int i = 0; i < 10; i++) {
if (count1[i] != count2[i]) {
return 0;
}
}
return 1;
}
int main() {
int n;
printf("请输入一个正整数:");
scanf("%d", &n);
printf("%d以内的同构数有:\n", n);
for (int i = 1; i <= n; i++) {
if (isIsomorphic(i)) {
printf("%d ", i);
}
}
printf("\n");
return 0;
}
```
上述程序中,定义了一个 `isIsomorphic` 函数来判断一个数是否是同构数。该函数首先计算出该数的平方,然后分别统计该数和它的平方中各个位上的数字出现的次数,最后比较两个计数数组是否相同,如果相同,则该数是同构数,返回 1,否则返回 0。
在 `main` 函数中,先读入一个正整数 n,然后遍历 1 到 n 之间的每一个数,判断它是否是同构数,如果是,则输出该数。最后输出所有同构数即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)