[the summarization of algorithm]How to list the prime number
来源:互联网 发布:工商网络监管工作总结 编辑:程序博客网 时间:2024/04/29 10:12
In order to get the list of prime number, I find some ways to do that.
素数判定法:
1、朴素的方法:
#include<stdio.h>bool isprime(int n);//判断是否是质数的函数int main(){int n;scanf("%d",&n);if(isprime(n))printf("%d is a prime.\n",n);elseprintf("%d isn't a prime.\n",n);return 0;}bool isprime(int n){int i;for(i = 2;i < n; i++)//原理:利用质数的定义:质数是只能被1和其本身整除的数{if(n % i == 0)break;}if(i == n)return true;elsereturn false;}
复杂度:o(n)
bool isprime(int n){int i;for(i = 2;i < n/2; i++)//一阶改进原理:只要2至n/2之间的数都不能被n整除,那么n就是质数(因为n/(n/2) = 2,n/((n/2)+k)<2)(k>0){if(n % i == 0)break;}if(i == n/2)return true;elsereturn false;}
复杂度:o(n/2)
bool isprime(int n){int i;for(i = 2;i <= (int)sqrt((double)n); i++)//改进原理:只要2至根号n之间的数不能被n整除,n即为质数。{if(n % i == 0)break;}if(i == (int)sqrt((double)n)+1)return true;elsereturn false;}原理:若n(n∈N,n>1)不能被小于根号n的所有质数整除,则n为质数。
复杂度:O(sqrt(n))
解释:非质数都可以分解为更小的质数乘积的形式,至于为什么是根号n,因为假如x=ab的话,那么ab一定一个小于等于根号另一个大于等于,所以a>根号n的时候b一定<根号n,所以到根号就相当于把所有可能的a都测试过一遍了。
4、埃拉托色尼筛选法(The sieve of Eratosthenes)
埃拉托色尼选筛法(the Sieve of Eratosthenes)简称埃氏筛法,是古希腊数学家埃拉托色尼(Eratosthenes 274B.C.~194B.C.)提出的一种筛选法。 是针对自然数列中的自然数而实施的,用于求一定范围内的质数。
步骤:1)先把1删除(现今数学界1既不是质数也不是合数)
2)读取2,并把2的倍数删除
3)读取3,并把3的倍数删除
4)读取5,并把5的倍数删除(4是2的倍数,在第2步已经被删除)
5)如上所述,直到所需范围你所有数字被读取过
#include<stdio.h>#include<stdlib.h>#define N 1000 //N以内的素数表int main(){bool chart[N+1];for(int i = 2;i<N;i++){if(chart[i])for(int j = 2*i;j<N;j+=i)chart[j] = false;}for(int i = 2;i<N;i++){if(chart[i])printf("%d\n",i);}return 0;}
0 0
- [the summarization of algorithm]How to list the prime number
- [the summarization of algorithm]Heap and Heapsort
- SOJ3605 The sum of prime number
- How to calculate the number of parameters of Convolutional Neural Networks(CNNs) correctly?
- How to Calculate the Number of IOPS and Throughput of a Database (文档 ID 2206831.1)
- Find the Prime Number
- How to retrive the IMSI number
- 转:How to submit the rows of a repeating table in InfoPath to a SharePoint list
- The power of algorithm
- How to choose the number of topics/partitions in a Kafka cluster?
- How to arrange 10 digits so that the product of the some of them is equal to a number represented by the remaining digits
- how to know the type of browser
- how to change the port of tomcat
- How to break out of the forEach
- how to ruin the all of Internet?
- How to use the function of assembly.
- How the ECDSA algorithm works
- How the backpropagation algorithm works
- Linked List Cycle
- 大型互联网公司的产品选择的技术
- 关于UIImage的图片处理(截图,合并图片)
- MySql SDK 编程 简单查询
- 打造受欢迎的邮件营销欢迎信
- [the summarization of algorithm]How to list the prime number
- mybatis中文教程
- Spring MVC handlerMapping和handlerAdapter
- 最小物联网系统设计——使用说明
- 互联网女皇的互联网报告2013版(详细)
- Struts学习笔记
- 大多数人不去行动
- ubuntu服务器源配置
- 《Effective C++》学习笔记条款31:将文件间的编译依存关系降至最低