C程序接受整数,如果它是Prime或Not Prime [英] C program to take integer if it is Prime or Not Prime

查看:276
本文介绍了C程序接受整数,如果它是Prime或Not Prime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有完全C语言的程序代码,并且效果很好,但结果不正确.我在下面的代码源.谁能帮助我发生了什么事或我错过了什么?欢迎大家更正此英语或代码.

I have this C program codes are completely and it's works very well, but not the correct result. I have them code source here in the below. Can anyone help me what is going on or what did I missing? Everyone are welcome to correct this English or code.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
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;
}

我制作了一个名为isprime的函数,如果传递给它的整数为质数,则返回true(即1),如果是复合数(即非素数),则返回false(即0). 2或任何奇数直到数字本身的平方根,否则为质数.对它进行编程后,输出结果不是我期望的参考值.

I made 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. After I programmed it, the output isn't what I expected the reference.

已编译:

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

推荐答案

问题是输入值9872349871太大,无法容纳32位整数.

The problem is that the input value, 9872349871, is too large to fit into a 32-bit integer.

您需要重写程序以使用long long而不是int(这将为您提供64位整数),并且为了解析命令行参数,您需要将atoi切换为.

You need to rewrite the program to use long long instead of int (this should give you a 64-bit integer) and in order to parse the command line parameter you will want to switch atoi to atoll.

注意事项:如果您的isprime实现(问题中未显示)通过将值自身乘以(a*a <= b)来避免平方根检查(a <= sqrt(b)),该平方值可能会溢出甚至64位整数的限制.因此,您可能需要使用a <= b/a修改该功能,例如 .

Caveat: If your isprime implementation (which wasn't shown in the question) avoids the square root check (a <= sqrt(b)) by multiplying a value by itself (a*a <= b), that squared value may overflow the limits of even a 64-bit integer. So you may need to revise that function, e.g. with a <= b/a.

这篇关于C程序接受整数,如果它是Prime或Not Prime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆