我需要编写一个程序,例如,当给定数字 879 时,必须检查该数字是否为素数,以及它的所有数字子序列是否都是素数,意思是 87、79、8、7、9 等。到目前为止,我已经做了一个函数检查一个数字是否是素数,但不知道如何将一个数字拆分为其数字子序列。
4 回答
让x数字。您可以先确定 的位数n, x。例如,如果x = 543689那么n = 6. 这很容易通过对数确定,例如(可通过 获得math.h)。中的每个数字在范围内x都有一个地址 , 。使用从右到左的顺序是很自然的,因此在上面的示例中对应于数字 9 而不是 5。i0,1,...,n-1i=0
设置一个嵌套的 for 循环,该循环遍历所有i,j带有0 <= i <= j <n. 每次通过内部循环时,您都需要获取带有起始索引i和结束索引的数字j。您可以分两步执行此操作
1) 让y = x % (10^(j+1)). 这将y等于最左边数字是 index 的子字符串j。例如,if x = 543689and j = 4then 10^5 = 100000and 543689 % 100000 = 43689-- 从索引 4 开始的子序列。
2)除以y-10^i这将把所有东西都扔到右边的地方i。例如,如果i=2然后。请注意,436 是 543689 的一部分,最左边的索引为 4,最右边的索引为 2。y = 43689y / 100 = 436
C 没有内置的幂运算符。您可以适当地初始化intvars 以保持权力10^(j+1),10^i并在每次通过循环时适当地更新这些权力(乘以 10)。
这是这些想法的 Python 实现(Python 因为我不想给 C,因为这听起来像家庭作业)。唯一可能无法自我解释的是//——这是 Python 中的整数除法。在 C 中,您可以使用/-- 假设您正在处理int变量:
x = 879
n = 3
for i in range(n):
for j in range(i,n):
y = x % 10**(j+1)
y = y // 10**i
print(y)
输出:
9
79
879
7
87
8
您也可以使用它(来源:find all subsequences of a number)
#include <stdio.h>
#define NUM 154
int main(void) {
int i,num=NUM,x,y,mask,digits=0,max=1;
while ( num != 0 ) {
num /= 10;
digits++;
}
for ( i = 1; i <= digits; i++ ) {
max *= 2;
}
printf("Subsequences are:\n");
for ( i = 1; i < max - 1 ; i++ ) {
mask = i;
x = 1;
num = NUM;
y=0;
while ( num != 0 ) {
if ( mask % 2 == 1 ) {
y += num % 10 * x;
x *= 10;
}
num /= 10;
mask /= 2;
}
printf("%d \n" , y);
}
return 0;
}
#include <stdio.h>
void isPrime(int n){
printf("%d is ...\n", n);
}
int main (void){
int theNumber = 879;
int base = 10;
int n, sub_n;
do {
for(n = theNumber; n >= base/10; n /= 10){
sub_n = n % base;
isPrime(sub_n);
}
base *= 10;
} while(sub_n != theNumber);
return 0;
}
您可以使用:
void chckdigits(int number)
{
int digits[10]= {0};
int i= 0;
while (number) {
digits[i]= number%10; // array is in reverse
number= number/10;
i++;
}
// now check all permutations
}