最近遇到很多问题都跟Prime有关,于是总结一下:

Prime definition:A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number. So 1 is not a prime, but 2 is a prime.

性质:

先说composite number:Every composite number has at least one prime factor less than or equal to square root of itself. composite又必须含有divisor other than 1 and itself, 所以必须在[2 ,] inclusive之间有可以整除的prime factor

所以prime number的性质就是:在 [2 ,] inclusive 之间找不到一个数i 使得 n % i == 0

问题1:Efficient program to print all prime factors of a given number

Given a number n, write an efficient function to print all prime factors of n. For example, if the input number is 12, then output should be “2 2 3″. And if the input number is 315, then output should be “3 3 5 7″.

Following are the steps to find all prime factors.
1) While n is divisible by 2, print 2 and divide n by 2.
2) After step 1, n must be odd. Now start a loop from i = 3 to square root of n. While i divides n, print i and divide n by i, increment i by 2 and continue.
3) If n is a prime number and is greater than 2, then n will not become 1 by above two steps. So print n if it is greater than 2.

 // A function to print all prime factors of a given number n
void primeFactors(int n)
{
// Print the number of 2s that divide n
while (n% == )
{
printf("%d ", );
n = n/;
} // n must be odd at this point. So we can skip one element (Note i = i +2)
for (int i = ; i <= sqrt(n); i = i+)
{
// While i divides n, print i and divide n
while (n%i == )
{
printf("%d ", i);
n = n/i;
}
} // This condition is to handle the case whien n is a prime number
// greater than 2
if (n > )
printf ("%d ", n);
}

测试一下上述程序

int main()
{
int n = ;
primeFactors(n);
return ;
}

输出

   

要特别注意12行sqrt(n)中的n是一直随 n = n / i 更新的,而不是始终都是最初始的n。这相当于是在找新的n的prime factor, 而且确定这个新的n的prime factor不包括之前找到过的 i,因为前面已经把小的prime factor全找出来了。反正只要 n 还是 composite number, 那么一定有一个prime factor小于sqrt(n), 那么就一定能找到新的 i 满足条件。找不到就说明 n 不是 composite number了。所以,最后跳出while循环是因为要么n变成了1,要么n变成了质数

当然不这么设置 i 的范围也可以,可以设置 i 从3 到最初的sqrt(n), 或者甚至n,这样可以,但是浪费时间。

How does this work?
The steps 1 and 2 take care of composite numbers and step 3 takes care of prime numbers. To prove that the complete algorithm works, we need to prove that steps 1 and 2 actually take care of composite numbers. This is clear that step 1 takes care of even numbers. And after step 1, all remaining prime factor must be odd (difference of two prime factors must be at least 2), this explains why i is incremented by 2.
Now the main part is, the loop runs till square root of n not till. To prove that this optimization works, let us consider the following property of composite numbers.
Every composite number has at least one prime factor less than or equal to square root of itself.
This property can be proved using counter statement. Let a and b be two factors of n such that a*b = n. If both are greater than , then a.b >  which contradicts the expression “a * b = n”.

In step 2 of the above algorithm, we run a loop and do following in loop
a) Find the least prime factor i (must be less than )
b) Remove all occurrences i from n by repeatedly dividing n by i.
c) Repeat steps a and b for divided n and i = i + 2. The steps a and b are repeated till n becomes either 1 or a prime number.

问题2: 写一个判断自然数n是不是prime的函数

 public class Solution {
public boolean isPrime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int i=3; i<=Math.sqrt(n); i=i+2) {
if (n % i == 0) return false;
}
return true;
}
}

Wiki上也给出了这个算法:The property of being prime (or not) is called primality. A simple but slow method of verifying the primality of a given number n is known as trial division. It consists of testing whether n is a multiple of any integer between 2 and . Algorithms much more efficient than trial division have been devised to test the primality of large numbers. Particularly fast methods are available for numbers of special forms, such as Mersenne numbers. As of April 2014, the largest known prime number has 17,425,170 decimal digits.

问题3:

Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.
For example, if n is 10, the output should be “2, 3, 5, 7″. If n is 20, the output should be “2, 3, 5, 7, 11, 13, 17, 19″.

The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million or so (Ref Wiki).

Following is the algorithm to find all the prime numbers less than or equal to a given integer n by Eratosthenes’ method:

  1. Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n).
  2. Initially, let p equal 2, the first prime number.
  3. Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list. These numbers will be 2p, 3p, 4p, etc.; note that some of them may have already been marked.
  4. Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3.

When the algorithm terminates, all the numbers in the list that are not marked are prime.

 #include <stdio.h>
#include <string.h> // marks all mutiples of 'a' ( greater than 'a' but less than equal to 'n') as 1.
void markMultiples(bool arr[], int a, int n)
{
int i = , num;
while ( (num = i*a) <= n )
{
arr[ num- ] = ; // minus 1 because index starts from 0.
++i;
}
} // A function to print all prime numbers smaller than n
void SieveOfEratosthenes(int n)
{
// There are no prime numbers smaller than 2
if (n >= )
{
// Create an array of size n and initialize all elements as 0
bool arr[n];
memset(arr, , sizeof(arr)); /* Following property is maintained in the below for loop
arr[i] == 0 means i + 1 is prime
arr[i] == 1 means i + 1 is not prime */
for (int i=; i<n; ++i)
{
if ( arr[i] == )
{
//(i+1) is prime, print it and mark its multiples
printf("%d ", i+);
markMultiples(arr, i+, n);
}
}
}
} // Driver Program to test above function
int main()
{
int n = ;
printf("Following are the prime numbers below %d\n", n);
SieveOfEratosthenes(n);
return ;
}

Summary: Prime的更多相关文章

  1. csu 1756: Prime

    1756: Prime Submit Page   Summary   Time Limit: 3 Sec     Memory Limit: 128 Mb     Submitted: 281    ...

  2. Summary of Critical and Exploitable iOS Vulnerabilities in 2016

    Summary of Critical and Exploitable iOS Vulnerabilities in 2016 Author:Min (Spark) Zheng, Cererdlong ...

  3. 三个不常用的HTML元素:<details>、<summary>、<dialog>

    前面的话 HTML5不仅新增了语义型区块级元素及表单类元素,也新增了一些其他的功能性元素,这些元素由于浏览器支持等各种原因,并没有被广泛使用 文档描述 <details>主要用于描述文档或 ...

  4. Java 素数 prime numbers-LeetCode 204

    Description: Count the number of prime numbers less than a non-negative number, n click to show more ...

  5. Prime Generator

    Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate ...

  6. POJ 2739. Sum of Consecutive Prime Numbers

    Sum of Consecutive Prime Numbers Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 20050 ...

  7. [LeetCode] Summary Ranges 总结区间

    Given a sorted integer array without duplicates, return the summary of its ranges. For example, give ...

  8. UVa 524 Prime Ring Problem(回溯法)

    传送门 Description A ring is composed of n (even number) circles as shown in diagram. Put natural numbe ...

  9. Network Basic Commands Summary

    Network Basic Commands Summary set or modify hostname a)     temporary ways hostname NEW_HOSTNAME, b ...

随机推荐

  1. input type="number"时,maxlength不起作用怎么解决

    最近小颖在做公司的angular项目时,发现当input type="number"时,maxlength不起作用,百度了下解决方式,顺便记录下,以便后期查看嘻嘻 <inpu ...

  2. centos 7安装jdk、tomcat

    jdk安装 创建上传目录: [root@ckl1 home]# pwd /home [root@ckl1 home]# mkdir upload 安装上传工具: yum install lrzsz 上 ...

  3. 【CF720D】Slalom 扫描线+线段树

    [CF720D]Slalom 题意:一个n*m的网格,其中有k个矩形障碍,保证这些障碍不重叠.问你从(1,1)走到(n,m),每步只能往右或往上走,不经过任何障碍的方案数.两种方案被视为不同,当且仅当 ...

  4. iOS - 开源框架、项目和学习资料汇总(网络篇)

    网络连接 1. AFNetworking – ASI不升级以后,最多人用的网络连接开源库,[推荐]iOS网络编程之AFNetworking使用,iOS开发下载文件速度计算.2. Alamofire – ...

  5. HOJ-1005 Fast Food(动态规划)

    Fast Food My Tags (Edit) Source : Unknown Time limit : 3 sec Memory limit : 32 M Submitted : 3777, A ...

  6. java 内存深度解析

    java 中的包括以下几大种的内存区域:1.寄存器    2.stack(栈) 3.heap(堆) 4.数据段 5.常量池 那么相应的内存区域中又存放什么东西(主要介绍 stack heap)? 栈: ...

  7. 图论——最小生成树_prim

    今天是最小生成树的prim的算法,因为本人水平有限所以堆优化都不是很会啊,但邻接表好像出了点小差错所以上邻接矩阵比较好一点,尽管比Kruskal慢了很多很多但这种贪心思想还是要学习的.从第一条边开始取 ...

  8. LoadRunner-创建场景

    录制完脚本,并调试运行正常后,想要模拟并发进行压力测试,需要创建场景. 1.点击Tools->Create Controller Scenario... 2.选择手工场景,并设置并发用户数.点击 ...

  9. 算法抽象及用Python实现具体算法

    一.算法抽象 它们一般是在具体算法的基础上总结.提炼.分析出来的,再反过来用于指导解决其它问题.它们适用于某一类问题的解决,用辩 证法的观点看,抽象的算法和具体的算法就是抽象与具体.普遍性与特殊性.共 ...

  10. 对SQL SERVER数据类型理解最好的一篇文章

    字符串前加N SQL SERVER中生成的语句中,字符串前加N,N 前缀必须是大写字母,是Unicode编码的意思. 一般来说,英文字符是一个字节组成,但是国际上的字太多了,因此就用两个字节来表示字符 ...