用C语言求一组数字的整数除数



我想在函数中做到这一点:我如何在C程序中发现一个数字是否可被2,3,4,5,6,8,9,25和125整除,而不使用%操作符和可整除规则?基数应为10*

使用可除性规则,你必须和数字打交道。也许任务假定没有除法(至少以显式形式-您可以从字符串表示中提取数字)

可被2整除,检查最后一位数字是否在0,2,4,6,8

集合中可被4整除,检查最后一位数字+前一位的两倍是否在0,4,8集合中。如果结果大于10,重复(88=>2*8+8=24=>2*2+4=8)

8的情况类似,但sumlast + 2*previous + 4*second_from_the_end(512 => 4*5+2*1+2=24=>2*2+4=8)

可被整除5,检查最后一位数字是否在set0,5中,25情况类似125年,

可被整除3,将所有数字相加,重复上述过程,直到结果为<10. 所谓"数字根";9的可整除性与0,3,6,9类似.

62检查可整除性and3

我不擅长C,所以我的例子可能很奇怪(ideone检查)

#include <stdio.h>
int divby3(int n) {
char s[10];
do {
sprintf(s, "%d", n);  //transform 72 to char buffer "72"
n = 0;
int i = 0;
while(s[i])  //until nil (end of string) found, we can also use for loop
n += s[i++] - 0x30;  //get difference of current char and char "0"

}
while (n >= 10);    //until 1-digit value

return (n==0) || (n==3) || (n==6) || (n==9);
}
int divby5(int n) {
char s[10];
int len = sprintf(s, "%d", n);
n = s[len - 1] - 0x30;  //last digit
return (n==0) || (n==5);
}
int main(void) {
printf("%d", divby3(72));  //try 71
return 0;
}

一个使用a - (a / b * b)实现模数运算符的函数:

bool isDivisible(int a, int b)
{
if((a - (a / b * b)) == 0) return true;
return false;
}

用法:

int main(void)
{  
int a = 8;
int b = 4;
int c = 3;

bool res = isDivisible(a,b);
bool res2 = isDivisible(a,c);

return 0;
}  

编辑-解决注释中的问题:
"我如何用可除性规则表示这样的程序?谢谢你的代码,我忘了说我必须在每个函数中使用可除规则">

下面展示了如何将可除性规则作为参数传入…

const int div_1[] = {2, 3, 4, 5, 6, 8, 9, 25, 125};
const int div_2[] = {7, 5, 17, 12, 11};
int main()
{   
size_t size = 0;

size = sizeof div_1/sizeof div_1[0];
bool res = isDivisible(2*3*4*5*6*8*9*25*125, div_1, size);
size = sizeof div_2/sizeof div_2[0];
bool res2 = isDivisible(125, div_2, size);

return 0;
}
//              numerator   divisor array    array size
bool isDivisible(long a, long div_rules[], size_t size)
{
//divisibility rules
const int divisors[] = {2, 3, 4, 5, 6, 8, 9, 25, 125};

for(int i = 0; i<size;i++)
{
if((a - (a / div_rules[i] * div_rules[i])) != 0) return false;
}
return true;
}

最新更新