简体   繁体   English

整数类型long和除法

[英]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. 如果将数据类型定义为“ int ”,它将正常工作;如果将其更改为“ long ”,则结果将是错误的。 I don't know why. 我不知道为什么

BTW, I used Win-TC as my compiler. 顺便说一句,我使用Win-TC作为编译器。

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. 应将%d替换为%ld。

Your function DividerIsPrime ,as currently written, has the defect that logically it must always return True . 当前编写的函数DividerIsPrime具有逻辑上必须始终返回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) . 即使达到status=False (数字是复合的,因为除法器的模数为零),迭代仍将继续,并且在每种情况下,当除法器==时,最终迭代将达到status=True (数据- 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". 显然,有更有效的“素数测试”算法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM