从函数中的Interger填入或未填入

时间:2018-10-31 21:03:44

标签: c primes

我不明白为什么它不输出预期的结果。我已经重做了三遍,但是无论int是否是素数,它都无法正确输出。

/**
 * Make a function called isprime that returns true (i.e. 1) if the integer
 * number passed to it is prime and false (i.e. 0) if it is composite (i.e.
 * not prime.)  A number is composite if it is divisible by 2 or any odd number
 * up to the square root of the number itself, otherwise it is prime.
 * Hint: n is divisible by m if (n % m == 0)
 */

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

int isprime(unsigned long long n) {
  unsigned long long m;
  for (m = 2; m <= n/m; m++) {
    if (n%m == 0) {
      return false;
    }
  }
  return n > 1;
}

/**
 * Using the isprime function you made above, test if a number provided on the
 * command line is prime or not. The program should print a usage message if no
 * number is provided ("Usage: p4 <number>\n") and print a warning if the number
 * is less than 2 ("input number should be > 1\n") and should be able to handle
 * numbers greater than 4 billion.
 *
 * Example input/output:
 * ./p4 9872349901
 * 9872349901 is prime
 * ./p4 65
 * 65 is not prime
 */

int main (int argc, char *argv[])
{
  int n;
  int result;

  if (argc < 2)
    {
      printf ("Usage: p4 <number>\n");
    }
  n = atoi (argv[1]);

  if (n < 2)
    {
      printf ("input number should be > 1\n");
    }
  result = isprime (n);

  if (result == 1)
    printf ("%d is prime\n", n);
  else
    printf ("%d is not prime\n", n);
  return 0;
}

已更新

检查后编译:

> p4:
> Output of program (p4) is not correct for input '9872349871':
> ------ Yours: ------ 
> 1282415279 is not prime
> ---- Reference: ---- 
> 9872349871 is not prime
> --------------------

1 个答案:

答案 0 :(得分:2)

  

'isprime()'不起作用,但我现在经常经常使用此功能,但是为什么不起作用?

setBackground(new Color(0, 128, 0));->从主要测试返回void isprime (int n)是没有意义的。这是致命的设计缺陷。

由于void具有isprime(int n)return 0;函数。致命错误。此应该使用功能良好的编译器发出警告。 启用所有警告以节省时间。

void isprime (int n)对于if ((fmod(n, m)) == 0)自变量int毫无意义。我希望n,m。在这里,转换为浮点的效率非常低,并且当if (n%m == 0)精度超过int时,作为主要测试通常不正确。

double范围通常不足以达到40亿范围内的值。推荐最宽的 unsigned 类型。要处理int,请使用9872349901unsigned long long@Fred Larson

uintmax_t对于大型非素数for (m = 2; m <= n - 1; m++)来说非常慢。仅迭代到平方根:当商超过除数时。

nisprime(0)返回错误的结果。

备用

isprime(1)
对于int isprime(unsigned long long n) { unsigned long long m; for (m = 2; m <= n/m; m++) { if (n%m == 0) { return false; } } return n > 1; }

许多性能优化是可能的。 Primality test