r/dailyprogrammer • • Jan 16 '15
[2015-01-16] Challenge #197 [Hard] Crazy Professor
Description
He's at it again, the professor at the department of Computer Science has posed a question to all his students knowing that they can't brute-force it. He wants them all to think about the efficiency of their algorithms and how they could possibly reduce the execution time.
He posed the problem to his students and then smugly left the room in the mindset that none of his students would complete the task on time (maybe because the program would still be running!).
The problem
What is the 1000000th number that is not divisble by any prime greater than 20?
Acknowledgements
Thanks to /u/raluralu for this submission!
NOTE
counting will start from 1. Meaning that the 1000000th number is the 1000000th number and not the 999999th number.
7
u/JHappyface Jan 17 '15
Using some Haskell magic (aka recursion) and a ton of optimizing, I came up with this nice little code based on Hamming numbers.
I really liked this challenge actually. I thought the problem was really easy to understand, and I had an initial code written in a few minutes. But it was slow. Prohibitively slow. So I rethought the problem. Learned some things. Did a lot of pencil and paper work. I hope to see more like this in the future.
10
u/kazagistar 0 1 Jan 16 '15 edited Jan 17 '15
Rust. Runs in around 0.2 seconds on my old nehalem i7.
Program:
Solution:
EDIT: Here is the explanation for how the algorithm works.
EDIT2: Oh man, I wasn't running it with any compiler optimizations. Adjusted the time by... quite a bit. (2.5s -> 0.20s)
EDIT3: Moved the explaining part to a gist to make it readable but still not too much of a "spoiler".
EDIT4: Updated to the newer and neater slice and range syntax (thanks #rust irc!). Also, ordering the multiple primes in reverse order is indeed about 20% faster... it is actually surprising that optimization worked.
9
u/curtmack Jan 16 '15 edited Jan 16 '15
Java
Hey, it's a hard challenge I actually know how to do! Doing this in Java instead of Clojure because this involves a lot of Java standard library objects and I'm more comfortable working with those in real Java than in Clojure.
Output:
Edit: I spent an hour or so optimizing the code a little bit. The current mean execution time is about 6.4 seconds. (Used to be 9.3 seconds, for reference.) I don't think it's possible to optimize much further, since the bulk of that time comes from object allocation and BigInteger arithmetic, and I've already eliminated these as much as possible.
Edit 2: Removed some extraneous code leftover from previous optimization attempts. It didn't substantially improve the execution time, though.
Edit 3: For people who don't understand what this solution is doing - read the problem description more carefully. You're looking for numbers that are not divisible by any prime number greater than 20. Prime numbers are divisible by themselves, therefore, there are no prime numbers greater than 20 on this list.
3
u/[deleted] Jan 17 '15 edited Jan 17 '15
Python 2, takes around 35 seconds:
Output:
1000000 24807446830080 (210 * 37 * 51 * 70 * 110 * 130 * 171 * 194)
3
u/mosqutip Jan 17 '15
C++, runs in ~120-150ms on my computer.
Disclaimer: I saw the suggestion of Hamming numbers here, and did some research on n-Smooth numbers as a result, which led to this answer.
3
u/NarcissusGray Jan 19 '15 edited Jan 19 '15
Python
Algorithmically its just an expansion on Dijkstra's classical solution to the Hamming Problem, optimized with generators for speed.
Output:
2
u/Im_not_JB Jan 16 '15 edited Jan 16 '15
EDIT: Yep. This is definitely broken. Just ignore it for now. I'll edit again if I think I've fixed it.
Solution in MATLAB:
Having done a lot of Project Euler problems, I guessed immediately that a sieve might work. The drawback of a sieve is always memory usage. My laptop can handle logical arrays that are about 3e9 long. I'm cheating a little by using MATLAB's built-in primes function (because I'm lazy and don't feel like firing up my FORTRAN compiler today). Thankfully, I only need the primes to go up to the sqrt of the length of my array, which is easily done (my lappy can handle ~4-5e8 in the primes function before it starts breaking, so with the max being 5e4, this is easy peasy.). I tested the code with small exponents and only needed to go up to 3e6 to find a solution. It took about a half second to run. The answer I got was
2
u/NoobOfProgramming Jan 18 '15
I did some reading on these types of number, and it looks like there's a pretty good formula for estimating how many there are. http://en.wikipedia.org/wiki/Smooth_number http://en.wikipedia.org/wiki/Regular_number http://en.wikipedia.org/wiki/Dickman_function
The nth number that is not divisible by any prime greater than 20 should be slightly greater than
2
u/Whats_Calculus Jan 20 '15
I've taken number theory so I had an easier time with this.
C++11:
2
u/theHawke Feb 13 '15 edited Feb 13 '15
Haskell, runs in under a second (
Data.List.Orderedis from the packagedata-ordlist):divisiblesrecursively generates all numbers divisible by the primes below 20 (and 1) which is equivalent to the numbers not divisible by any prime greater than 20.Result is the same as for everyone else in this thread.
1
u/[deleted] Jan 16 '15
C#. No idea if this answer is correct or not. SortedSet came in pretty handy here for what I had in mind.
1
u/ChiefSnoopy Jan 16 '15 edited Jan 16 '15
So I think I need some serious help optimizing here... Please, please, please be brutal with your suggestions and don't hold back. This is not the first time I've had to deal with myself writing poorly optimized code and I need to kick the habit.
The solution that this gives me is 3583964. I don't even know if that's correct as I haven't seen matching answers yet.
If you think you have a suggestion, don't hold back. I'm not unwilling to try things.
Note: That create_primes_generator function is derived from some code that I've seen online in a lot of places (namely floating around reddit). I do not take credit for writing that.
EDIT: If it gives you any idea of how bad the time is... Time elapsed: -1421443154.9319882
1
u/rwendesy Jan 16 '15 edited Jan 16 '15
Solution in Java
After generating a list of primes up to a certain limit, I created a boolean[] array that held true if not divisible. I looped through each of the primes, +=themselves and at the appropriate index of the boolean array, made it false (divisible). After this, I then counted the number of true variables in the boolean array, and when I reached 1,000,000 I printed it.
I had an output of:
I have no idea if it is right, but it is my first time coming at least close to being right on a hard question, I'm excited!
I took the Sieve of Atkin from this post: http://stackoverflow.com/questions/10580159/sieve-of-atkin-explanation-and-java-example
1
u/Godspiral 3 3 Jan 16 '15 edited Jan 17 '15
In J,
answers the wrong problem: The 1e6th number that is not divisible by a prime below 20.
brute force triangulation without much memory or time
(p: i.8) ([: +/ -.@:(0&e.)@:|"1 0) (>: i.22) NB. only 1 number up to 22
1
(p: i.8) ([: +/ -.@:(0&e.)@:|"1 0) (>: i.23) NB. 23 is 2nd number
2
(p: i.8) ([: +/ -.@:(0&e.)@:|"1 0) (>: i.2022)
342
Not exact answer but spoils:
999965
1
u/ununiqueusername Jan 16 '15
This is my first attempt at one of these. This seemed like a pretty safe and straight-forward approach, but my answer is several times larger than others have produced, so it's probably wrong.
Written in Python 2.7.6.
Answer:
Any clues as where I went wrong, or how I've misinterpreted the problem?
1
u/[deleted] Jan 16 '15
Rust translation of my C# solution. This one skips the sorted set. I originally used that because I had thought I might want to try it with multiple threads (which I skipped in the end) and because I would then have trouble figuring out what the biggest value was, since it would--probably--not be in order anymore... Anyway, if you add things in order, it works fine to just have an array full of them and then constantly check the last one in the array.
Whatever.
The borrow checker is feeling a lot less annoying these days. That's good.
This solution runs in about two seconds on my digital ocean box. Not sure how long it would take on a real computer. /shrug
Bad news: this doesn't get the same answer as the other one does. :)
1
u/Qyaffer Jan 17 '15 edited Jan 17 '15
Java
I've tested my solution for the first 6000 and it works flawlessly.
However my solution is EXTREMELY slow. It would take hours if not days for it to calculate the 1000000th number. My solution may be straight forward and accurate, but it is horribly optimized. That is something that I really need to work on.
Here is my solution, rip it apart please, I need to know if/what I did wrong ! :
1
u/NoobOfProgramming Jan 17 '15 edited Jan 17 '15
Fairly straightforward C++ solution, help/criticism is much appreciated.
EDIT: I turned on compiler optimization, and it now takes ~80 ms instead of ~3000; I had no idea the compiler could optimize so much!
EDIT: Here's the answer i got:
1
u/Godspiral 3 3 Jan 18 '15 edited Jan 19 '15
A fast and simpler J version
creates a list of the numbers that are below a set value (0 X). 1 X is prime factors
X =: 1 : 'm &{::@:['
If you forget 17 in the prime list then 1Mth number is: (10 seconds or so)
1
u/yitz Jan 19 '15 edited Jan 22 '15
Haskell. The main part of the algorithm is the function
onlyDivisibleByAllowed, which is a one-liner.Runs in under 5 secs. on my 4-year-old machine. I left out type signatures to keep it simple, so it is using
Integer(big ints) by default. If I specialize the types toInt, the time goes down to 4.5 secs. With ugly hairy optimization and/or adding a fewparoperators to utilize multiple cores, it could be much faster.1
u/chronoslynx Jan 20 '15 edited Jan 20 '15
Here's a solution in rust nightly as of 01/20/2015 at 3pm EST using an algorithm from RosettaCode:
Made a generator for B-smooth numbers and shoved 20 into it. Produces the one-millionth number: 24807446830080 and does so quite quickly:
EDIT: Building with
cargo build --releaseproduces the following:Well damn.
EDIT 2: Altered the code to implement the Iterator trait and use
dropinstead of my silly loop.1
u/VikingofRock Jan 21 '15
Short C++11; takes about 2.5 seconds when compiled with -Ofast.
Output:
I had to think a lot about how to do this, and I know I could have been a lot smarter about it with a more complicated data structure (like a heap or something). But whatever this works!
1
u/MuffinsLovesYou 0 1 Jan 16 '15 edited Jan 16 '15
But Brofessor, brute force is all I know how to do. C#, the string at the end of the constructor is where I put my breakpoint to look at the output.
Fires in about 2-3 seconds.
Edit Edit: I grabbed and modified the prime calculation logic from http://stackoverflow.com/questions/1042902/most-elegant-way-to-generate-prime-numbers
}
1
u/ih8l33t Jan 16 '15 edited Jan 17 '15
C# single thread solution..... (first time posting, re-edited a few times for formatting)
my output is:
0
u/[deleted] Jan 16 '15
[deleted] — view deleted comment