Celia Zou
Celia Zou

Reputation: 13

integer type long and division

I just write a procedure to decompose an unsigned integer to prime numbers. it will work normally if I define the data type as "int", if I change it to "long", result will be wrong. I don't know why.

BTW, I used Win-TC as my compiler.

Code as below:

#include "stdio.h"
#define True    0xff
#define False   0x00
char DividerIsPrime(unsigned long data);
void CheckIfDataCanBeExtracted(unsigned long data);
main()
{
    unsigned long data;
    printf("please input data:");
    scanf("%d",&data);
    printf("\n%d=",data);
    CheckIfDataCanBeExtracted(data);
//    printf("%d",sizeof(short));
    getch();
}

void CheckIfDataCanBeExtracted(unsigned long data)
{
    unsigned long divider,temp,data1;
    data1=data;
    for(divider=2;divider<=data;divider++)
    {
         temp=data1%divider;
         if(temp) {continue;  }
         if(DividerIsPrime(divider)) {
        data1 = data1/divider;
        printf("%d",divider);
        if(data1==1) break;

        else {printf("*");  divider--;}


      }
    }
    return;

}

/* Check if this number is a prime number */
char DividerIsPrime(unsigned long data)
{
    unsigned long divider;
    char    status=True;
    for(divider=2;divider<data;divider++)
    {
        if(data%divider) status=True;
        else status=False;
    }
    return status;
}

Thanks for Paul's help, I know where is wrong. %d should be replaced by %ld.

Upvotes: 0

Views: 1630

Answers (1)

Heath Hunnicutt
Heath Hunnicutt

Reputation: 19467

Your function DividerIsPrime,as currently written, has the defect that logically it must always return True.

The reason for this is that status is changed at each iteration. Even if status=False is reached (the number is composite because the modulus came out zero for a divider), then the iterations will continue and in every case, status=True will be reached on the final iteration when divider == (data - 1).

You can change this as follows:

/* Check if this number is a prime number */
char DividerIsPrime(unsigned long data)
{
    unsigned long divider;
    for(divider=2;divider<data;divider++)
    {
        if (0==(data % divider))
            return False;
    }

    return True;
}

You would have found this with some "unit test" such as:

assert(DividerIsPrime(5));
assert(!DividerIsPrime(6));  /* This test would fail without corrected code. */

Obviously there are much more efficient algorithms for "primality testing".

Upvotes: 1

Related Questions