Search Results

Search found 107 results on 5 pages for 'primes'.

Page 1/5 | 1 2 3 4 5  | Next Page >

  • Fastest way to list all primes below N in python

    - by jbochi
    This is the best algorithm I could come up with after struggling with a couple of Project Euler's questions. def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes >>> timeit.Timer(stmt='get_primes.get_primes(1000000)', setup='import get_primes').timeit(1) 1.1499958793645562 Can it be made even faster? EDIT: This code has a flaw: Since numbers is an unordered set, there is no guarantee that numbers.pop() will remove the lowest number from the set. Nevertheless, it works (at least for me) for some input numbers: >>> sum(get_primes(2000000)) 142913828922L #That's the correct sum of all numbers below 2 million >>> 529 in get_primes(1000) False >>> 529 in get_primes(530) True EDIT: The rank so far (pure python, no external sources, all primes below 1 million): Sundaram's Sieve implementation by myself: 327ms Daniel's Sieve: 435ms Alex's recipe from Cookbok: 710ms EDIT: ~unutbu is leading the race.

    Read the article

  • Finding the nth number of primes

    - by Braxton Smith
    I can not figure out why this won't work. Please help me from math import sqrt pN = 0 numPrimes = 0 num = 1 def checkPrime(x): '''Check\'s whether a number is a prime or not''' prime = True if(x==2): prime = True elif(x%2==0): prime=False else: root=int(sqrt(x)) for i in range(3,root,2): if(x%i==0): prime=False break return prime n = int(input("Find n number of primes. N being:")) while( numPrimes != n ): if( checkPrime( num ) == True ): numPrimes += 1 pN = num print("{0}: {1}".format(numPrimes,pN)) num += 1 print("Prime {0} is: {1}".format(n,pN))

    Read the article

  • Help with Java Program for Prime numbers

    - by Ben
    Hello everyone, I was wondering if you can help me with this program. I have been struggling with it for hours and have just trashed my code because the TA doesn't like how I executed it. I am completely hopeless and if anyone can help me out step by step, I would greatly appreciate it. In this project you will write a Java program that reads a positive integer n from standard input, then prints out the first n prime numbers. We say that an integer m is divisible by a non-zero integer d if there exists an integer k such that m = k d , i.e. if d divides evenly into m. Equivalently, m is divisible by d if the remainder of m upon (integer) division by d is zero. We would also express this by saying that d is a divisor of m. A positive integer p is called prime if its only positive divisors are 1 and p. The one exception to this rule is the number 1 itself, which is considered to be non-prime. A positive integer that is not prime is called composite. Euclid showed that there are infinitely many prime numbers. The prime and composite sequences begin as follows: Primes: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, … Composites: 1, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, … There are many ways to test a number for primality, but perhaps the simplest is to simply do trial divisions. Begin by dividing m by 2, and if it divides evenly, then m is not prime. Otherwise, divide by 3, then 4, then 5, etc. If at any point m is found to be divisible by a number d in the range 2 d m-1, then halt, and conclude that m is composite. Otherwise, conclude that m is prime. A moment’s thought shows that one need not do any trial divisions by numbers d which are themselves composite. For instance, if a trial division by 2 fails (i.e. has non-zero remainder, so m is odd), then a trial division by 4, 6, or 8, or any even number, must also fail. Thus to test a number m for primality, one need only do trial divisions by prime numbers less than m. Furthermore, it is not necessary to go all the way up to m-1. One need only do trial divisions of m by primes p in the range 2 p m . To see this, suppose m 1 is composite. Then there exist positive integers a and b such that 1 < a < m, 1 < b < m, and m = ab . But if both a m and b m , then ab m, contradicting that m = ab . Hence one of a or b must be less than or equal to m . To implement this process in java you will write a function called isPrime() with the following signature: static boolean isPrime(int m, int[] P) This function will return true or false according to whether m is prime or composite. The array argument P will contain a sufficient number of primes to do the testing. Specifically, at the time isPrime() is called, array P must contain (at least) all primes p in the range 2 p m . For instance, to test m = 53 for primality, one must do successive trial divisions by 2, 3, 5, and 7. We go no further since 11 53 . Thus a precondition for the function call isPrime(53, P) is that P[0] = 2 , P[1] = 3 , P[2] = 5, and P[3] = 7 . The return value in this case would be true since all these divisions fail. Similarly to test m =143 , one must do trial divisions by 2, 3, 5, 7, and 11 (since 13 143 ). The precondition for the function call isPrime(143, P) is therefore P[0] = 2 , P[1] = 3 , P[2] = 5, P[3] = 7 , and P[4] =11. The return value in this case would be false since 11 divides 143. Function isPrime() should contain a loop that steps through array P, doing trial divisions. This loop should terminate when 2 either a trial division succeeds, in which case false is returned, or until the next prime in P is greater than m , in which case true is returned. Function main() in this project will read the command line argument n, allocate an int array of length n, fill the array with primes, then print the contents of the array to stdout according to the format described below. In the context of function main(), we will refer to this array as Primes[]. Thus array Primes[] plays a dual role in this project. On the one hand, it is used to collect, store, and print the output data. On the other hand, it is passed to function isPrime() to test new integers for primality. Whenever isPrime() returns true, the newly discovered prime will be placed at the appropriate position in array Primes[]. This process works since, as explained above, the primes needed to test an integer m range only up to m , and all of these primes (and more) will already be stored in array Primes[] when m is tested. Of course it will be necessary to initialize Primes[0] = 2 manually, then proceed to test 3, 4, … for primality using function isPrime(). The following is an outline of the steps to be performed in function main(). • Check that the user supplied exactly one command line argument which can be interpreted as a positive integer n. If the command line argument is not a single positive integer, your program will print a usage message as specified in the examples below, then exit. • Allocate array Primes[] of length n and initialize Primes[0] = 2 . • Enter a loop which will discover subsequent primes and store them as Primes[1] , Primes[2], Primes[3] , ……, Primes[n -1] . This loop should contain an inner loop which walks through successive integers and tests them for primality by calling function isPrime() with appropriate arguments. • Print the contents of array Primes[] to stdout, 10 to a line separated by single spaces. In other words Primes[0] through Primes[9] will go on line 1, Primes[10] though Primes[19] will go on line 2, and so on. Note that if n is not a multiple of 10, then the last line of output will contain fewer than 10 primes. Your program, which will be called Prime.java, will produce output identical to that of the sample runs below. (As usual % signifies the unix prompt.) % java Prime Usage: java Prime [PositiveInteger] % java Prime xyz Usage: java Prime [PositiveInteger] % java Prime 10 20 Usage: java Prime [PositiveInteger] % java Prime 75 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 % 3 As you can see, inappropriate command line argument(s) generate a usage message which is similar to that of many unix commands. (Try doing the more command with no arguments to see such a message.) Your program will include a function called Usage() having signature static void Usage() that prints this message to stderr, then exits. Thus your program will contain three functions in all: main(), isPrime(), and Usage(). Each should be preceded by a comment block giving it’s name, a short description of it’s operation, and any necessary preconditions (such as those for isPrime().) See examples on the webpage.

    Read the article

  • Why are primes important in cryptography?

    - by Michael Stum
    One thing that always strikes me as a non-cryptographer: Why is it so important to use Prime numbers? What makes them so special in cryptography? Does anyone have a simple short explanation? (I am aware that there are many primers and that Applied Cryptography is the Bible, but as said: I am not looking to implement my own cryptographic algorithm, and the stuff that I found just made my brain explode - no 10 pages of math formulas please :)) Thanks for all the answers. I've accepted the one that made the actual concept most clear to me.

    Read the article

  • Prime Numbers Code Help

    - by andrew
    Hello Everybody, I am suppose to "write a Java program that reads a positive integer n from standard input, then prints out the first n prime number." It's divided into 3 parts. 1st: This function will return true or false according to whether m is prime or composite. The array argument P will contain a sufficient number of primes to do the testing. Specifically, at the time isPrime() is called, array P must contain (at least) all primes p in the range 2 p m . For instance, to test m = 53 for primality, one must do successive trial divisions by 2, 3, 5, and 7. We go no further since 11 53 . Thus a precondition for the function call isPrime(53, P) is that P[0] = 2 , P[1] = 3 , P[2] = 5, and P[3] = 7 . The return value in this case would be true since all these divisions fail. Similarly to test m =143 , one must do trial divisions by 2, 3, 5, 7, and 11 (since 13 143 ). The precondition for the function call isPrime(143, P) is therefore P[0] = 2 , P[1] = 3 , P[2] = 5, P[3] = 7 , and P[4] =11. The return value in this case would be false since 11 divides 143. Function isPrime() should contain a loop that steps through array P, doing trial divisions. This loop should terminate when 2 either a trial division succeeds, in which case false is returned, or until the next prime in P is greater than m , in which case true is returned. Then there is the "main function" • Check that the user supplied exactly one command line argument which can be interpreted as a positive integer n. If the command line argument is not a single positive integer, your program will print a usage message as specified in the examples below, then exit. • Allocate array Primes[] of length n and initialize Primes[0] = 2 . • Enter a loop which will discover subsequent primes and store them as Primes[1] , Primes[2], Primes[3] , ……, Primes[n -1] . This loop should contain an inner loop which walks through successive integers and tests them for primality by calling function isPrime() with appropriate arguments. • Print the contents of array Primes[] to stdout, 10 to a line separated by single spaces. In other words Primes[0] through Primes[9] will go on line 1, Primes[10] though Primes[19] will go on line 2, and so on. Note that if n is not a multiple of 10, then the last line of output will contain fewer than 10 primes. The last function is called "usage" which I am not sure how to execute this! Your program will include a function called Usage() having signature static void Usage() that prints this message to stderr, then exits. Thus your program will contain three functions in all: main(), isPrime(), and Usage(). Each should be preceded by a comment block giving it’s name, a short description of it’s operation, and any necessary preconditions (such as those for isPrime().) And hear is my code, but I am having a bit of a problem and could you guys help me fix it? If I enter the number "5" it gives me the prime numbers which are "6,7,8,9" which doesn't make much sense. import java.util.; import java.io.; import java.lang.*; public class PrimeNumber { static boolean isPrime(int m, int[] P){ int squarert = Math.round( (float)Math.sqrt(m) ); int i = 2; boolean ans=false; while ((i<=squarert) & (ans==false)) { int c= P[i]; if (m%c==0) ans= true; else ans= false; i++; } /* if(ans ==true) ans=false; else ans=true; return ans; } ///****main public static void main(String[] args ) { Scanner in= new Scanner(System.in); int input= in.nextInt(); int i, j; int squarert; boolean ans = false; int userNum; int remander = 0; System.out.println("input: " + input); int[] prime = new int[input]; prime[0]= 2; for(i=1; i ans = isPrime(j,prime); j++;} prime[i] = j; } //prnt prime System.out.println("The first " + input + " prime number(s) are: "); for(int r=0; r }//end of main } Thanks for the help

    Read the article

  • Find out 20th, 30th, nth prime number. (I'm getting 20th but not 30th?) [Python]

    - by gsin
    The question is to find the 1000th prime number. I wrote the following python code for this. The problem is, I get the right answer for the 10th , 20th prime but after that each increment of 10 leaves me one off the mark. I can't catch the bug here :( count=1 #to keep count of prime numbers primes=() #tuple to hold primes candidate=3 #variable to test for primes while count<20: for x in range(2,candidate): if candidate%x==0: candidate=candidate+2 else : pass primes=primes+(candidate,) candidate=candidate+2 count=count+1 print primes print "20th prime is ", primes[-1] In case you're wondering, count is initialised as 1 because I am not testing for 2 as a prime number(I'm starting from 3) and candidate is being incremented by 2 because only odd numbers can be prime numbers. I know there are other ways of solving this problem, such as the prime number theorem but I wanna know what's wrong with this approach. Also if there are any optimisations you have in mind, please suggest. Thank You

    Read the article

  • Have I checked every consecutive subset of this list?

    - by Nathan
    I'm trying to solve problem 50 on Project Euler. Don't give me the answer or solve it for me, just try to answer this specific question. The goal is to find the longest sum of consecutive primes that adds to a prime below one million. I use wrote a sieve to find all the primes below n, and I have confirmed that it is correct. Next, I am going to check the sum of each subset of consecutive primes using the following method: I have a empty list sums. For each prime number, I add it to each element in sums and check the new sum, then I append the prime to sums. Here it is in python primes = allPrimesBelow(1000000) sums = [] for p in primes: for i in range(len(sums)): sums[i] += p check(sums[i]) sums.append(p) I want to know if I have called check() for every sum of two or more consecutive primes below one million The problem says that there is a prime, 953, that can be written as the sum of 21 consecutive primes, but I am not finding it.

    Read the article

  • Correct answer will not output

    - by rEgonicS
    I made a program that returns the sum of all primes under 2 million. I really have no idea what's going on with this one, I get 142891895587 as my answer when the correct answer is 142913828922. It seems like its missing a few primes in there. I'm pretty sure the getPrime function works as it is supposed to. I used it a couple times before and worked correctly than. The code is as follows: vector<int> getPrimes(int number); int main() { unsigned long int sum = 0; vector<int> primes = getPrimes(2000000); for(int i = 0; i < primes.size(); i++) { sum += primes[i]; } cout << sum; return 0; } vector<int> getPrimes(int number) { vector<bool> sieve(number+1,false); vector<int> primes; sieve[0] = true; sieve[1] = true; for(int i = 2; i <= number; i++) { if(sieve[i]==false) { primes.push_back(i); unsigned long int temp = i*i; while(temp <= number) { sieve[temp] = true; temp = temp + i; } } } return primes; }

    Read the article

  • [0-9a-zA-Z]* string expressed with primes or prime-factorization-style way to break it into parts?

    - by HH
    Suppose a string consists of numbers and alphabets. You want to break it into parts, an analogy is primes' factorization, but how can you do similar thing with strings [0-9a-zA-Z]* or even with arbitrary strings? I could express it in alphabets and such things with octal values and then prime-factorize it but then I need to keep track of places where I had the non-numbers things. Is there some simple way to do it? I am looking for simple succinct solutions and don't want too much side-effects. [Update] mvds has the correct idea, to change the base, how would you implement it?

    Read the article

  • Project Euler 7 Scala Problem

    - by Nishu
    I was trying to solve Project Euler problem number 7 using scala 2.8 First solution implemented by me takes ~8 seconds def problem_7:Int = { var num = 17; var primes = new ArrayBuffer[Int](); primes += 2 primes += 3 primes += 5 primes += 7 primes += 11 primes += 13 while (primes.size < 10001){ if (isPrime(num, primes)) primes += num if (isPrime(num+2, primes)) primes += num+2 num += 6 } return primes.last; } def isPrime(num:Int, primes:ArrayBuffer[Int]):Boolean = { // if n == 2 return false; // if n == 3 return false; var r = Math.sqrt(num) for (i <- primes){ if(i <= r ){ if (num % i == 0) return false; } } return true; } Later I tried the same problem without storing prime numbers in array buffer. This take .118 seconds. def problem_7_alt:Int = { var limit = 10001; var count = 6; var num:Int = 17; while(count < limit){ if (isPrime2(num)) count += 1; if (isPrime2(num+2)) count += 1; num += 6; } return num; } def isPrime2(n:Int):Boolean = { // if n == 2 return false; // if n == 3 return false; var r = Math.sqrt(n) var f = 5; while (f <= r){ if (n % f == 0) { return false; } else if (n % (f+2) == 0) { return false; } f += 6; } return true; } I tried using various mutable array/list implementations in Scala but was not able to make solution one faster. I do not think that storing Int in a array of size 10001 can make program slow. Is there some better way to use lists/arrays in scala?

    Read the article

  • Use QuickCheck by generating primes

    - by Dan
    Background For fun, I'm trying to write a property for quick-check that can test the basic idea behind cryptography with RSA. Choose two distinct primes, p and q. Let N = p*q e is some number relatively prime to (p-1)(q-1) (in practice, e is usually 3 for fast encoding) d is the modular inverse of e modulo (p-1)(q-1) For all x such that 1 < x < N, it is always true that (x^e)^d = x modulo N In other words, x is the "message", raising it to the eth power mod N is the act of "encoding" the message, and raising the encoded message to the dth power mod N is the act of "decoding" it. (The property is also trivially true for x = 1, a case which is its own encryption) Code Here are the methods I have coded up so far: import Test.QuickCheck -- modular exponentiation modExp :: Integral a => a -> a -> a -> a modExp y z n = modExp' (y `mod` n) z `mod` n where modExp' y z | z == 0 = 1 | even z = modExp (y*y) (z `div` 2) n | odd z = (modExp (y*y) (z `div` 2) n) * y -- relatively prime rPrime :: Integral a => a -> a -> Bool rPrime a b = gcd a b == 1 -- multiplicative inverse (modular) mInverse :: Integral a => a -> a -> a mInverse 1 _ = 1 mInverse x y = (n * y + 1) `div` x where n = x - mInverse (y `mod` x) x -- just a quick way to test for primality n `divides` x = x `mod` n == 0 primes = 2:filter isPrime [3..] isPrime x = null . filter (`divides` x) $ takeWhile (\y -> y*y <= x) primes -- the property prop_rsa (p,q,x) = isPrime p && isPrime q && p /= q && x > 1 && x < n && rPrime e t ==> x == (x `powModN` e) `powModN` d where e = 3 n = p*q t = (p-1)*(q-1) d = mInverse e t a `powModN` b = modExp a b n (Thanks, google and random blog, for the implementation of modular multiplicative inverse) Question The problem should be obvious: there are way too many conditions on the property to make it at all usable. Trying to invoke quickCheck prop_rsa in ghci made my terminal hang. So I've poked around the QuickCheck manual a bit, and it says: Properties may take the form forAll <generator> $ \<pattern> -> <property> How do I make a <generator> for prime numbers? Or with the other constraints, so that quickCheck doesn't have to sift through a bunch of failed conditions? Any other general advice (especially regarding QuickCheck) is welcome.

    Read the article

  • Project Euler 10: (Iron)Python

    - by Ben Griswold
    In my attempt to learn (Iron)Python out in the open, here’s my solution for Project Euler Problem 10.  As always, any feedback is welcome. # Euler 10 # http://projecteuler.net/index.php?section=problems&id=10 # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # Find the sum of all the primes below two million. import time start = time.time() def primes_to_max(max): primes, number = [2], 3 while number < max: isPrime = True for prime in primes: if number % prime == 0: isPrime = False break if (prime * prime > number): break if isPrime: primes.append(number) number += 2 return primes primes = primes_to_max(2000000) print sum(primes) print "Elapsed Time:", (time.time() - start) * 1000, "millisecs" a=raw_input('Press return to continue')

    Read the article

  • Efficiently storing a list of prime numbers

    - by eSKay
    This article says: Every prime number can be expressed as 30k±1, 30k±7, 30k±11, or 30k±13 for some k. That means we can use eight bits per thirty numbers to store all the primes; a million primes can be compressed to 33,334 bytes "That means we can use eight bits per thirty numbers to store all the primes" This "eight bits per thirty numbers" would be for k, correct? But each k value will not necessarily take-up just one bit. Shouldn't it be eight k values instead? "a million primes can be compressed to 33,334 bytes" I am not sure how this is true. We need to indicate two things: VALUE of k (can be arbitrarily large) STATE from one of the eight states (-13,-11,-7,-1,1,7,11,13) I am not following how 33,334 bytes was arrived at, but I can say one thing: as the prime numbers become larger and larger in value, we will need more space to store the value of k. How, then can we fix it at 33,334 bytes?

    Read the article

  • Clojure: Avoiding stack overflow in Sieve of Erathosthene?

    - by nixx
    Here's my implementation of Sieve of Erathosthene in Clojure (based on SICP lesson on streams): (defn nats-from [n] (iterate inc n)) (defn divide? [p q] (zero? (rem q p))) (defn sieve [stream] (lazy-seq (cons (first stream) (sieve (remove #(divide? (first stream) %) (rest stream)))))) (def primes (sieve (nats-from 2))) Now, it's all OK when i take first 100 primes: (take 100 primes) But, if i try to take first 1000 primes, program breaks because of stack overflow. I'm wondering if is it possible to change somehow function sieve to become tail-recursive and, still, to preserve "streamnes" of algorithm? Any help???

    Read the article

  • How to make efficient code emerge through unit testing

    - by Jean
    Hi, I participate in a TDD Coding Dojo, where we try to practice pure TDD on simple problems. It occured to me however that the code which emerges from the unit tests isn't the most efficient. Now this is fine most of the time, but what if the code usage grows so that efficiency becomes a problem. I love the way the code emerges from unit testing, but is it possible to make the efficiency property emerge through further tests ? Here is a trivial example in ruby: prime factorization. I followed a pure TDD approach making the tests pass one after the other validating my original acceptance test (commented at the bottom). What further steps could I take, if I wanted to make one of the generic prime factorization algorithms emerge ? To reduce the problem domain, let's say I want to get a quadratic sieve implementation ... Now in this precise case I know the "optimal algorithm, but in most cases, the client will simply add a requirement that the feature runs in less than "x" time for a given environment. require 'shoulda' require 'lib/prime' class MathTest < Test::Unit::TestCase context "The math module" do should "have a method to get primes" do assert Math.respond_to? 'primes' end end context "The primes method of Math" do should "return [] for 0" do assert_equal [], Math.primes(0) end should "return [1] for 1 " do assert_equal [1], Math.primes(1) end should "return [1,2] for 2" do assert_equal [1,2], Math.primes(2) end should "return [1,3] for 3" do assert_equal [1,3], Math.primes(3) end should "return [1,2] for 4" do assert_equal [1,2,2], Math.primes(4) end should "return [1,5] for 5" do assert_equal [1,5], Math.primes(5) end should "return [1,2,3] for 6" do assert_equal [1,2,3], Math.primes(6) end should "return [1,3] for 9" do assert_equal [1,3,3], Math.primes(9) end should "return [1,2,5] for 10" do assert_equal [1,2,5], Math.primes(10) end end # context "Functionnal Acceptance test 1" do # context "the prime factors of 14101980 are 1,2,2,3,5,61,3853"do # should "return [1,2,3,5,61,3853] for ${14101980*14101980}" do # assert_equal [1,2,2,3,5,61,3853], Math.primes(14101980*14101980) # end # end # end end and the naive algorithm I created by this approach module Math def self.primes(n) if n==0 return [] else primes=[1] for i in 2..n do if n%i==0 while(n%i==0) primes<<i n=n/i end end end primes end end end

    Read the article

  • Goldbach theory in C

    - by nofe
    I want to write some code which takes any positive, even number (greater than 2) and gives me the smallest pair of primes that sum up to this number. I need this program to handle any integer up to 9 digits long. My aim is to make something that looks like this: Please enter a positive even integer ( greater than 2 ) : 10 The first primes adding : 3+7=10. Please enter a positive even integer ( greater than 2 ) : 160 The first primes adding : 3+157=160. Please enter a positive even integer ( greater than 2 ) : 18456 The first primes adding : 5+18451=18456. I don't want to use any library besides stdio.h. I don't want to use arrays, strings, or anything besides for the most basic toolbox: scanf, printf, for, while, do-while, if, else if, break, continue, and the basic operators (<,, ==, =+, !=, %, *, /, etc...). Please no other functions especially is_prime. I know how to limit the input to my needs so that it loops until given a valid entry. So now I'm trying to figure out the algorithm. I thought of starting a while loop like something like this: #include <stdio.h> long first, second, sum, goldbach, min; long a,b,i,k; //indices int main (){ while (1){ printf("Please enter a positive integer :\n"); scanf("%ld",&goldbach); if ((goldbach>2)&&((goldbach%2)==0)) break; else printf("Wrong input, "); } while (sum!=goldbach){ for (a=3;a<goldbach;a=(a+2)) for (i=2;(goldbach-a)%i;i++) first = a; for (b=5;b<goldbach;b=(b+2)) for (k=2;(goldbach-b)%k;k++) sum = first + second; } }

    Read the article

  • Recursive function causing a stack overflow

    - by dbyrne
    I am trying to write a simple sieve function to calculate prime numbers in clojure. I've seen this question about writing an efficient sieve function, but I am not to that point yet. Right now I am just trying to write a very simple (and slow) sieve. Here is what I have come up with: (defn sieve [potentials primes] (if-let [p (first potentials)] (recur (filter #(not= (mod % p) 0) potentials) (conj primes p)) primes)) For small ranges it works fine, but causes a stack overflow for large ranges: user=> (sieve (range 2 30) []) [2 3 5 7 11 13 17 19 23 29] user=> (sieve (range 2 15000) []) java.lang.StackOverflowError (NO_SOURCE_FILE:0) I thought that by using recur this would be a non-stack-consuming looping construct? What am I missing?

    Read the article

  • Help making this code run faster for spoj.

    - by Josh Meredith
    I've been doing a few of the challenges on the Sphere Online Judge, but I can't seem to get the second problem (the prime generator) to run within the time limit. Does anyone have any tips for increasing the speed of the following code? #include <stdio.h> #include <math.h> int is_prime(int n); void make_sieve(); void fast_prime(int n); int primes[16000]; int main() { int nlines; int m, n; make_sieve(); scanf("%d", &nlines); for (; nlines >= 1; nlines--) { scanf("%d %d", &m, &n); if (!(m % 2)) { m++; } for ( ; m < n; m+=2) { fast_prime(m); } printf("\n"); } return 0; } /* Prints a number if it's prime. */ inline void fast_prime(int n) { int j; for (int i = 0; ((j = primes[i]) > -1); i++) { if (!(n % j)) { return; } } printf("%d\n", n); } /* Create an array listing prime numbers. */ void make_sieve() { int j = 0; for (int i = 0; i < 16000; i++) { primes[i] = -1; } for (int i = 2; i < 32000; i++) { if (i % 2) { if (is_prime(i)) { primes[j] = i; j++; } } } return; } /* Test if a number is prime. Return 1 if prime. Return 0 if not. */ int is_prime(int n) { int rootofn; rootofn = sqrt(n); if ((n <= 2) || (n == 3) || (n == 5) || (n == 7)) { return 1; } if (((n % 2) == 0) || ((n % 3) == 0) || ((n % 5) == 0) || ((n % 7) == 0)) { return 0; } for (int i = 11; i < rootofn; i += 2) { if ((n % i) == 0) { return 0; } } return 1; }

    Read the article

  • why is this C++ Code not doing his job

    - by hamza
    i want to create a program that write all the primes in a file ( i know that its a popular algorithm but m trying to make it by my self ) , but it still showing all the numbers instead of just the primes , & i dont know why someone pleas tell me why #include <iostream> #include <stdlib.h> #include <stdio.h> void afficher_sur_un_ficher (FILE* ficher , int nb_bit ); int main() { FILE* p_fich ; char tab[4096] , mask ; int nb_bit = 0 , x ; for (int i = 0 ; i < 4096 ; i++ ) { tab[i] = 0xff ; } for (int i = 0 ; i < 4096 ; i++ ) { mask = 0x01 ; for (int j = 0 ; j < 8 ; j++) { if ((tab[i] & mask) != 0 ) { x = nb_bit ; while (( x > 1 )&&(x < 16384)) { tab[i] = tab[i] ^ mask ; x = x * 2 ; } afficher_sur_un_ficher (p_fich , nb_bit ) ; } mask = mask<<1 ; nb_bit++ ; } } system ("PAUSE"); return 0 ; } void afficher_sur_un_ficher (FILE* ficher , int nb_bit ) { ficher = fopen("res.txt","a+"); fprintf (ficher ,"%d \t" , nb_bit); int static z ; z = z+1 ; if ( z%10 == 0) fprintf (ficher , "\n"); fclose(ficher); }

    Read the article

  • Go and a bad prime number algorithm

    - by anonymous
    I wrote this prime number sieving algorithm and it doesn't run properly. I can't find the error in the algorithm itself. Could someone help me? This is what it's supposed to print: [2 3 5 7 11 13 17 19 23 29] Versus what it actually prints: [3 5 7 11 13 17 19 23 25 29] . package main import "fmt" func main() { var primes = sieve(makeNumbers(29)) fmt.Printf("%d\n", primes); } func makeNumbers(n int) []int { var numbers = make([]int, n - 1) for i := 0; i < len(numbers); i++ { numbers[i] = i + 2 } return numbers } func sieve(numbers []int) []int { var numCopy = numbers var max = numbers[len(numbers)-1] var sievedNumbers = make([]int, 0) for i := 0; numCopy[i]*numCopy[i] <= max; i++ { for j := i; j < len(numCopy); j++ { if numCopy[j] % numCopy[i] != 0 || j == i { sievedNumbers = append(sievedNumbers, numCopy[j]) } } numCopy = sievedNumbers sievedNumbers = make([]int, 0) } return numCopy }

    Read the article

  • Coup d'envoi d'Imagine Cup 2013 : Microsoft double le montant des primes du championnat de l'innovation numérique pour étudiant

    Coup d'envoi d'Imagine Cup 2013 : Microsoft double les primes et modifie la thématique de son championnat de l'innovation numérique pour étudiant C'est parti pour une nouvelle saison d'Imagine Cup, le championnat du monde étudiant de l'innovation numérique organisé par Microsoft. [IMG]http://rdonfack.developpez.com/images/imaginecup20132.jpg[/IMG] Créé en 2002, Imagine Cup permet à des étudiants du monde entier de « s'affronter » pour révéler leur potentiel créatif et entrepreneurial avec une mission : répondre à un ou plusieurs des « Objectifs du Millénaire pour le Développement ». L'édition 2013 de la compétition est ouverte dan...

    Read the article

  • Finding a prime number after a given number

    - by avd
    How can I find the least prime number greater than a given number? For example, given 4, I need 5; given 7, I need 11. I would like to know some ideas on best algorithms to do this. One method that I thought of was generate primes numbers through the Sieve of Eratosthenes, and then find the prime after the given number.

    Read the article

  • Enumerating large (20-digit) [probable] prime numbers

    - by Paul Baker
    Given A, on the order of 10^20, I'd like to quickly obtain a list of the first few prime numbers greater than A. OK, my needs aren't quite that exact - it's alright if occasionally a composite number ends up on the list. What's the fastest way to enumerate the (probable) primes greater than A? Is there a quicker way than stepping through all of the integers greater than A (other than obvious multiples of say, 2 and 3) and performing a primality test for each of them? If not, and the only method is to test each integer, what primality test should I be using?

    Read the article

1 2 3 4 5  | Next Page >