21xrx.com
2024-11-24 12:18:35 Sunday
登录
文章检索 我的文章 写文章
调用并输出结果 C++函数判断素数并输出结果
2023-07-06 12:37:49 深夜i     --     --
C++函数 素数 输出结果

素数是指只能被1和它本身整除的自然数。在计算机编程中,判断一个数是否为素数是一个常见的问题。下面介绍如何使用C++函数判断素数并输出结果。

首先,我们需要定义一个函数来判断一个数是否为素数。一个简单的算法是遍历2到这个数的平方根之间的所有自然数,看看是否有一个数能整除这个数。如果存在一个数能整除,则这个数就不是素数。否则,这个数就是素数。

下面是一个例子函数:


bool isPrime(int num){

  if(num < 2) return false;

  for(int i = 2; i <= sqrt(num); ++i){

    if(num % i == 0) return false;

  }

  return true;

}

这个函数接收一个整数参数num并返回一个bool值,表示num是否为素数。

接下来,我们可以在主函数中调用这个函数,判断一些数字是否为素数,并输出结果。例如,我们可以处理从1到100内的所有数字:


#include <iostream>

#include <cmath>

using namespace std;

bool isPrime(int num);

int main(){

  for(int i = 1; i <= 100; ++i){

    if(isPrime(i))

      cout << i << " is prime." << endl;

    

    else

      cout << i << " is not prime." << endl;

    

  }

  return 0;

}

bool isPrime(int num){

  if(num < 2) return false;

  for(int i = 2; i <= sqrt(num); ++i){

    if(num % i == 0) return false;

  }

  return true;

}

运行上面的代码,我们会得到如下的输出结果:


1 is not prime.

2 is prime.

3 is prime.

4 is not prime.

5 is prime.

6 is not prime.

7 is prime.

8 is not prime.

9 is not prime.

10 is not prime.

11 is prime.

12 is not prime.

13 is prime.

14 is not prime.

15 is not prime.

16 is not prime.

17 is prime.

18 is not prime.

19 is prime.

20 is not prime.

21 is not prime.

22 is not prime.

23 is prime.

24 is not prime.

25 is not prime.

26 is not prime.

27 is not prime.

28 is not prime.

29 is prime.

30 is not prime.

31 is prime.

32 is not prime.

33 is not prime.

34 is not prime.

35 is not prime.

36 is not prime.

37 is prime.

38 is not prime.

39 is not prime.

40 is not prime.

41 is prime.

42 is not prime.

43 is prime.

44 is not prime.

45 is not prime.

46 is not prime.

47 is prime.

48 is not prime.

49 is not prime.

50 is not prime.

51 is not prime.

52 is not prime.

53 is prime.

54 is not prime.

55 is not prime.

56 is not prime.

57 is not prime.

58 is not prime.

59 is prime.

60 is not prime.

61 is prime.

62 is not prime.

63 is not prime.

64 is not prime.

65 is not prime.

66 is not prime.

67 is prime.

68 is not prime.

69 is not prime.

70 is not prime.

71 is prime.

72 is not prime.

73 is prime.

74 is not prime.

75 is not prime.

76 is not prime.

77 is not prime.

78 is not prime.

79 is prime.

80 is not prime.

81 is not prime.

82 is not prime.

83 is prime.

84 is not prime.

85 is not prime.

86 is not prime.

87 is not prime.

88 is not prime.

89 is prime.

90 is not prime.

91 is not prime.

92 is not prime.

93 is not prime.

94 is not prime.

95 is not prime.

96 is not prime.

97 is prime.

98 is not prime.

99 is not prime.

100 is not prime.

可以看到,我们成功地使用了C++函数判断素数并输出结果。这个方法可以很方便地在实际编程中使用,用于解决各种问题。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复