tags:

views:

49

answers:

1

Hi all,

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.

+1  A: 

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".

Heath Hunnicutt
However, this defect should have been apparent with ints. Wonder why the poster thought the int/long difference was important.
djna
I changed the function you mentioned. but its result remails fail.
Celia Zou
Do you understand how the original function was incorrect and why? It sounds like you are only taking my word for the truth.
Heath Hunnicutt