Comparison in c incorrect for integers other than 2?

46 Views Asked by At

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

There are 1 best solutions below

0
YWH On

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!