英文:
Comparison in c incorrect for integers other than 2?
问题
我正在编写一个函数来确定一个数字的质因数,并将它们返回到一个双向链表中。代码如下。
DLL* primefactors(int a, DLL *factors){
int i;
int primes[40] = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 37, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173};
factors = create_list(1); // 从节点"1"开始创建
i = 0;
while(i < 40 && a != 1){
if (a % primes[i] == 0){
printf("%d 是 %d 的因数; ", primes[i], a);
add_to_tail(factors, primes[i]);
a = a / primes[i];
printf("余数是 %d\n", a);
} else {
printf("%d 不是 %d 的因数; 增加到 %d\n", primes[i], a, primes[i + 1]);
i++;
}
}
print_DLL(factors);
return factors;
}
该函数在测试因子为2的情况下工作正常,但无法识别更高的质因数。
例如,primefactors(8)
正确给出 1, 2, 2, 2;但 primefactors(24)
给出 1, 2, 2, 2,然后无法识别3为因子,而是运行到质数列表的末尾(请忽略列表开头的1)。
这是为什么,以及如何修复它呢?我认为 a / prime[i]
应该给出一个准确的整数,因为a和prime[i]都是整数,避免了浮点数比较问题。
谢谢!
英文:
I am writing a function to determine the prime factors of a number and return them in a doubly linked list. The code is as below.
(create_list, add_to_tail, and print_DLL perform operations on the DLL and work fine).
DLL* primefactors(int a, DLL *factors){
int i;
int primes[40] = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 37, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173};
factors = create_list(1); // create with node of "1" to begin with
i = 0;
while(i < 40 && a != 1){
if (a % primes[0] == 0){
printf("%d is a factor of %d; ", primes[i], a);
add_to_tail(factors, primes[0]);
a = a / primes[0];
printf("remainder is %d\n", a);
} else {
printf("%d is not a factor of %d; increasing to %d\n", primes[i], a, primes[i + 1]);
i++;
}
}
print_DLL(factors);
return factors;
}
The function works correctly for testing factors of 2, but does not recognise higher primes as factors.
e.g. primefactors(8)
correctly gives 1, 2, 2, 2; but primefactors(24)
gives 1, 2, 2, 2 and then doesn't recognise 3 as a factor, instead running to the end of the list of primes (ignore the 1 at the beginning of the list please).
Why is this and how can it be fixed please? I'd thought that a / prime[i]
would give an accurate integer as both a and prime[i] are ints, avoiding float comparison issues.
Thank you!
答案1
得分: 1
正如评论中Barmar和Some programmer dude指出的,除法应该是以primes[i]而不是primes[0]进行的。有了这个修正,它就可以正常工作了。谢谢!
英文:
As pointed out by Barmar and Some programmer dude in the comments, the division should be with primes[i] instead of primes[0]. With this correction it works. Thanks!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论