求大于整数m且紧靠m的k个素数 及 判断一个数是否为素数的方法

时间:2022-04-22
本文章向大家介绍求大于整数m且紧靠m的k个素数 及 判断一个数是否为素数的方法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目:

  请编写一个函数void fun(int m,int k ,int xx[]),该函数的功能是:将大于整数m且紧靠m的k个素数存入xx所指的数组中。

  例如,若输入:17,5,则应输出:19,23,29,31,37。

质数又称素数。指在一个大于1的自然数中,除了1和此整数自身外,不能被其他自然数整除的数。

 1 #include<stdio.h>
 2 #include<math.h>
 3  
 4 bool isPrime(int n)
 5 { 
 6     for(int i = 2 ; i <= sqrt(n) ; i++)
 7     {
 8         if(n % i == 0)
 9             return false;
10     }
11     return true;
12 }
13  
14 void fun(int m , int n , int xx[])
15 {
16     int count = 0;
17     for(int j = m + 1 ; count < n ; j++)
18     {
19         if(isPrime(j))
20         {
21             xx[count++] = j;                   
22         }      
23     }
24 }
25  
26 int main()
27 {
28     int m , n , zz[1000];
29     printf("please input two integers: ");
30     scanf("%d,%d",&m,&n);
31  
32     fun(m , n , zz);
33  
34     for( m = 0 ; m < n ; m++)
35     {
36         printf("%d  " , zz[m]);
37     }
38     printf("n");
39  
40     return 0;
41 }

 --------------------------------------------------------------------------------------------------------------------------------------------------------------

现在再看到上面写的代码,觉得以前写的代码,竟然开了那么大的数组,代码挺粗糙的。

 1 #include<iostream>
 2 #include<math.h>
 3 using namespace std;
 4  
 5 bool isPrime(int n)
 6 { 
 7     for(int i = 2 ; i <= sqrt(n) ; i++)
 8     {
 9         if(n % i == 0)
10             return false;
11     }
12     return true;
13 }
14  
15 void fun(int m , int n , int xx[])
16 {
17     int count = 0;
18     for(int j = m + 1 ; count < n ; j++)
19     {
20         if(isPrime(j))
21         {
22             xx[count++] = j;                   
23         }      
24     }
25 }
26  
27 int main()
28 {
29     int m , n ;
30     int *zz = new int[];
31 
32     cout<<"please input two integers:";
33     cin>>m>>n;
34  
35     fun(m , n , zz);
36  
37     for( m = 0 ; m < n ; m++)
38         cout<<zz[m]<<" ";
39 
40     cout<<endl;
41  
42     return 0;
43 }