C错误找到最大素数因子

时间:2014-02-02 00:17:15

标签: c primes

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <math.h>

bool isPrime(unsigned long long x) {
    if (x % 2 == 0)
        return false;
    for (unsigned long long i = 3; i < sqrt(x); x += 2) {
        if (x % i == 0)
            return false;
    }
    return true;
}

int main(int argc, char const *argv[]) {
    unsigned long long largest, number = 13195;

    for (unsigned long long i = 2; i < number; i++) {
        if (isPrime(i) && number % i == 0) {
            largest = i;
        }
    }

    printf("Largest : %llu\n", largest);

    return EXIT_SUCCESS;
}

Prime数功能是否有效? 如果我删除for循环中的sqrt(),我会得到0的结果,这很奇怪......

我的输出为7,但最大的素数应该是29 为什么会这样?

2 个答案:

答案 0 :(得分:4)

这里有一个拼写错误:

x += 2

应该是

i += 2

这会使您的isPrime(29)返回false


顺便说一句,为什么要这么麻烦?一个更简单的解决方案就是将数字分解:

unsigned long long number = 13195;
unsigned long long i, max = 2;
unsigned long long orig = number;

for (i = 2; i <= orig; i++) {
    while (number % i == 0) {
        number /= i;
        max = i;
    }
}

printf("largest: %llu\n", max);

答案 1 :(得分:1)

代码错误,更改

// for (unsigned long long i = 3; i < sqrt(x); x += 2) {
for (unsigned long long i = 3; i < sqrt(x); i += 2) {
//                                          ^

为了好玩,isPrime()简化:(长期有效)

bool isPrime(long long x) {
  if (x % 2 == 0)
    return x == 2;
  long long i = 1;
  lldiv_t qr;
  do {
    i += 2;
    qr = lldiv(x, i);
    if (qr.rem == 0) {
      return false;
    }
  } while (i < qr.quot);
  return true;
}