求大于整数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 }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值