Linear Sieve Method for Prime Numbers
来源:互联网 发布:韩国眼中的中国 知乎 编辑:程序博客网 时间:2024/06/05 15:30
Problem description:When we calculate for prime numbers with a sieve method,we delete so many numbers which is not necessary repeatly.For instance,there is a number which consists of 3x7x17x23,and we delete it when we delete the multiples of 3 as we delete the same number when we delete the multiples of 7,17,and 23.Please write a program that will not do these jobs more than once.
Thinking: There is a factorization theorem:every composite number could be decomposed into the multiplication of some primer numbers.Hence,the number can be decomposed in the form of (both of p andq are prime numbers and p < q).Therefore,what we need to remove is:,,...and,i=1,2,3.....The value of p and q is the numbers which are not removed currently and in a sequence from small to large.It is easy to write the program.
#include <stdio.h> #define MAX 1000 #define null1 0 #define NEXT(x) x=next[x] #define REMOVE(x) { previous[next[x]]=previous[x]; \ next[previous[x]]=next[x]; \ } #define INITIAL(n) { unsigned long i; \ for(i=2;i<=n;i++) \ previous[i]=i-1,next[i]=i+1; \ previous[2]=next[n]=null1; \ } int main() { unsigned long previous[MAX+1]={0}; unsigned long next[MAX+1]={0}; unsigned long prime,fact,i,mult; unsigned long n; unsigned long count=0; scanf("%lu",&n); INITIAL(n); //initial the array for(prime=2;prime*prime<=n;NEXT(prime)) { for(fact=prime;prime*fact<=n;NEXT(fact)) { for(mult=prime*fact;mult<=n;mult*=prime) REMOVE(mult); } } for(i=2;i!=null1;NEXT(i)) printf("%lu ",i),count++; printf("\nThe sum of the prime numbers is %lu\n",count); }
Reference material: C语言名题精选百则技巧篇 in Chinese.
- Linear Sieve Method for Prime Numbers
- A Sieve Method for Prime Numbers
- UVa11105 - Semi-prime H-numbers(sieve的思想)
- Sieve Prime 素数筛法
- C++ prime:the method for construct a sequential container
- sIEve
- linear conjugate gradient method
- prime numbers(素数)
- FOJ 1563 Prime Numbers
- FZU 1563 Prime Numbers
- hdoj_2138How many prime numbers
- How many prime numbers
- Prime Numbers(简单)
- How many prime numbers
- UVa10539 Almost Prime Numbers
- Find prime numbers
- sgu113:Nearly prime numbers
- 113. Nearly prime numbers
- android2.3 -添加自定义按键:作唤醒功能
- 示波器探头×1和×10的意义
- Uploadify上传Session丢失问题
- arm处理器裸机开发实战——学习笔记1
- mini2440 linux-3.7移植记录(二)
- Linear Sieve Method for Prime Numbers
- 饥渴的程序员
- Timer用法
- C语言算法(一)基础
- Markup Tags of magento CMS
- Servlet第五章、第六章知识点总结——Web应用程序状态管理、对象作用域
- 根据变量值获取变量名
- 如何理解stdlib.h里的_countof()宏
- 点击按钮——网页返回顶部代码