[email protected] Sieve of Eratosthenes (素数筛选算法) & Related Problem (Return two prime numbers )

Sieve of Eratosthenes (素数筛选算法)

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.

Explanation with Example:
Let us take an example when n = 50. So we need to print all print numbers smaller than or equal to 50.

We create a list of all numbers from 2 to 50.

According to the algorithm we will mark all the numbers which are divisible by 2.

Now we move to our next unmarked number 3 and mark all the numbers which are multiples of 3.

We move to our next unmarked number 5 and mark all multiples of 5.

We continue this process and our final table will look like below:

So the prime numbers are the unmarked ones: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47.

Related Practice Problem

http://www.practice.geeksforgeeks.org/problem-page.php?pid=425

Return two prime numbers

Given an even number ( greater than 2 ), return two prime numbers whose sum will be equal to given number. There are several combinations possible. Print only first such pair.

NOTE: A solution will always exist, read Goldbach’s conjecture.

Also, solve the problem in linear time complexity, i.e., O(n).

Input:

The first line contains T, the number of test cases. The following T lines consist of a number each, for which we‘ll find two prime numbers.

Note: The number would always be an even number.

Output:

For every test case print two prime numbers space separated, such that the smaller number appears first. Answer for each test case must be in a new line.

Constraints:

1 ≤ T ≤ 70
1 ≤ N ≤ 10000

Example:

Input:

5
74
1024
66 
8
9990

Output:

3 71
3 1021
5 61
3 5
17 9973

import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {

    public static void func(int n) {

        boolean[] prime = new boolean[n+1];
        for(int i=2; i<=n; ++i) {
            prime[i] = true;
        }

        for(int p=2; p*p<=n; ++p) {
            if(prime[p]) {
                for(int k=2*p; k<=n; k+=p) {
                    prime[k] = false;
                }
            }
        }

        ArrayList<Integer> rs = new ArrayList<Integer> ();
        for(int i=2; i<=n; ++i) {
            if(prime[i]) {
                rs.add(i);
            }
        }

        for(int i=0; i<rs.size(); ++i) {
            int first = rs.get(i);
            int second = n - first;
            if(prime[first] && prime[second]) {
                System.out.println(first + " " + second);
                break;
            }
        }
    }

    public static void main (String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();

        for(int i=0; i<t; ++i) {
            int n = in.nextInt();
            func(n);
        }
    }
}

时间: 2024-10-02 04:41:51

[email protected] Sieve of Eratosthenes (素数筛选算法) & Related Problem (Return two prime numbers )的相关文章

UVa 1210 (高效算法设计) Sum of Consecutive Prime Numbers

题意: 给出n,求把n写成若干个连续素数之和的方案数. 分析: 这道题非常类似大白书P48的例21,上面详细讲了如何从一个O(n3)的算法优化到O(n2)再到O(nlogn),最后到O(n)的神一般的优化. 首先筛出10000以内的素数,放到一个数组中,然后求出素数的前缀和B.这样第i个素数一直累加到第j个素数,就可表示为Bj - Bi-1 枚举连续子序列的右端点j,我们要找到Bj - Bi-1 = n,也就是找到Bi-1 = Bj - n. 因为Bj是递增的,所以Bi-1也是递增的,所以我们就

@codechef - [email&#160;protected] Random Number Generator

目录 @[email protected] @[email protected] @part - [email protected] @part - [email protected] @part - [email protected] @accepted [email protected] @[email protected] @[email protected] 给定递推关系式:\[A_i=C_1A_{i-1} + C_2A_{i-2}+\dots+C_kA_{i-k}\] 并给定 \(A_

UVA 10539 Almost Prime Numbers( 素数因子)

Problem AAlmost Prime NumbersTime Limit: 1 second Almost prime numbers are the non-prime numbers which are divisible by only a single prime number. In this problem your job is to write a program which finds out the number of almost prime numbers with

埃拉托色尼筛法(Sieve of Eratosthenes)求素数。

埃拉托色尼筛法(Sieve of Eratosthenes)是一种用来求所有小于N的素数的方法.从建立一个整数2~N的表着手,寻找i? 的整数,编程实现此算法,并讨论运算时间. 由于是通过删除来实现,而1和0则不是素数,所以从2,3,5以及其倍数删除. 用Data[]来储存所有的数,将替换好的数字存在Data[]当中 而只需做出将2,3,5以及能将这些数整除的数字替换为零:if(Data[j] % i == 0 ) Data[j]==0; 实现的代码段为: for (i = 2; i < n;

@算法 - [email&#160;protected] 后缀自动机

目录 @0 - 参考资料@ @0.5 - 引言@ @1 - what is [email protected] @自动机@ @DAWG@ @终点集合 [email protected] @后缀链接 与 parent 树@ @2 - how to build [email protected] @理论@ @代码@ @3 - where can it [email protected] @0 - 参考资料@ Menci's Blog 的讲解 陈立杰冬令营的课件 @0.5 - 引言@ 后缀自动机(Su

@算法 - [email&#160;protected] matrix - tree 定理(矩阵树定理)

目录 @0 - 参考资料@ @0.5 - 你所需要了解的线性代数知识@ @1 - 定理主体@ @证明 part - [email protected] @证明 part - [email protected] @证明 part - [email protected] @证明 part - 4@ @2 - 一些简单的推广@ @3 - 例题与应用@ @0 - 参考资料@ MoebiusMeow 的讲解(超喜欢这个博主的!) 网上找的另外一篇讲解 @0.5 - 你所需要了解的线性代数知识@ 什么是矩阵

ZZUOJ-1222- 属于ACMer的游戏 猜素数 (某月赛,总结一下素数筛选法)

题目位置:1222: 属于ACMer的游戏 猜素数 1222: 属于ACMer的游戏 猜素数 Time Limit: 1 Sec  Memory Limit: 128 MB Submit: 88  Solved: 21 [Submit][Status][Web Board] Description ACM实验室的众大神们喜欢聚餐大家一起HAPPY 尤其卢学长喜欢请大家HAPPY,但是卢学长请吃饭有一个习惯,大家要一起玩一个热身游戏,猜素数. 游戏规则如下: 正常人的版本是这样:比如卢学长先约定一

hdu 5407 CRB and Candies(素数筛选法,除法取模(乘法逆元))

题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=5407 解题思路: 官方题解: The problem is just to calculate g(N) =\ LCM(C(N,0), C(N,1), ..., C(N, N))g(N) = LCM(C(N,0),C(N,1),...,C(N,N)). Introducing function f(n) =\ LCM(1, 2, ..., n)f(n) = LCM(1,2,...,n), the

O(N)的素数筛选法和欧拉函数

首先,在谈到素数筛选法时,先涉及几个小知识点. 1.一个数是否为质数的判定. 质数,只有1和其本身才是其约数,所以我们判定一个数是否为质数,只需要判定2~(N - 1)中是否存在其约数即可,此种方法的时间复杂度为O(N),随着N的增加,效率依然很慢.这里有个O()的方法:对于一个合数,其必用一个约数(除1外)小于等于其平方根(可用反证法证明),所以我们只需要判断2-之间的数即可. bool is_prime(int num) { const int border = sqrt(num); for