/** * @author 冰樱梦 * 时间:2018年下半年 * 题目:求小于10000的素数的个数 * */ public class Exercise06_10 { public static void main(String[] args){ int sum=0; for(int i=1;i<=1000;i++){ if(isPrime(i))sum++; } System.out.println("1000以内素数的个数为 "+sum); } public static…
求1到n之间素数的个数 1. 筛选法 筛选掉偶数,然后比如对于 3,而言,筛选掉其整数倍数:(也即合数一定是某数的整数倍,比如 27 = 3*9) int n = 100000000; bool flag[100000000+1]; // flag[0] 无用的空间: int count() { int cnt = 0; flag[2] = 1; for (int i = 3; i < n; ++i) { flag[i++] = 1; // 奇数位 flag[i] = 0; // 偶数位直接过滤…
本文是对 LeetCode Count Primes 解法的探讨. 题目: Count the number of prime numbers less than a non-negative number, n. 尽管题目并没有要我们写一个最优的算法,但是身为一个程序员,优化应该是一种习惯,在编程的过程中,随着思考进行优化.只要求我们满足给定的时间和空间即可. 如果你只能想出一个最简单的方法,难道你会有什么竞争力吗? 穷举 最开始我用的就是这个方法,可以说这是最简单的一种方法了,而且最开始,我…
F. Four Divisors 题目连接: http://www.codeforces.com/contest/665/problem/F Description If an integer a is divisible by another integer b, then b is called the divisor of a. For example: 12 has positive 6 divisors. They are 1, 2, 3, 4, 6 and 12. Let's def…
int degree_in_fact(int n, int x)//求n!中素数x的次数 { if(m) return degree_in_fact(n/x,x)+n/x; ; }…
输出不大于N的素数的个数 Sieve of Eratosthenes 方法  素数的性质: 非素数可以分解为素数乘积. 证明 (1)n = 2 成立,n = 3 成立: (2)若 n = k 时成立,n = k+1时,假设 n = k+1 = k1*k2, 如果 k+1 是素数,k1 = 1, k2 = K+1, 成立: 如果 k+1不是素数,k1 <= k, k2 <= k, 两者都可以表示为素数乘积,所以 k+1可以表示为素数乘积.其它细节见程序注释, public class Prime…
有两种做法,一种是打表,另一种是直接求. 打表 将1e11每隔len(len=2000w)个数字统计一下该区间内素数的个数,比如cnt[1] 表示[1,len]以内有多少个素数,cnt[2]表示[len+1,2*len]以内有多少个素数,依次类推. 然后维护一下前缀和,sum[i] = cnt[1] + ....+ cnt[i] 那么给定一个数字n,求[1,n]以内有多少个素数, 那么只要统计一下sum[n/len],然后再统计一下区间[n/len*len+1, n/len*len + n%le…
Description 求n到m之间素数的个数 Input 多组测试数据,每组先输入一个整数t,表示组数,然后每组输入2个正整数n和m,(1 <= n <= m <= 10000) Output 每组一行,内容为一个整数,输出n到m之间素数的个数 Sample Input 1 2 3 Sample Output 2 #include<stdio.h> #include<math.h> int main() { int t; int i,j,k; int n,m;…
首先.我们谈一下素数的定义.什么是素数?除了1和它本身外,不能被其它自然数整除(除0以外)的数 称之为素数(质数):否则称为合数. 依据素数的定义,在解决问题上,一開始我想到的方法是从3到N之间每一个奇数进行遍历,然后再依照素数的定义去逐个除以3到 根号N之间的奇数,就能够计算素数的个数了. 于是便编写了以下的代码: (代码是用C++编写的) #include<iostream> #include <time.h> using namespace std; const int N…
最近在leetCode上刷提,还是满锻炼人的,为以后面试打基础吧.不多说下面开始. 问题:求[2,n]之间的素数的个数. 来源:leetCode OJ 提示: Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPri…