|
Thread Rules 1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution. 2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20) 3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible. 4. Use [code] tags to format code blocks. |
1019 Posts
I think this is better
for (int i = b; i <= a; i++) { for (int j = 2; j <= sqrt(i); j++) { if ((i%j != 0) && (i%2 != 0)) { cout << i << " is prime" << endl; } } }
The program keeps outputting 9 and 15 as prime numbers. I can understand why they are both outputted (they both satisfy the conditions in the if statement) but I don't know how to check that they are not prime.
|
On October 15 2012 14:49 mmp wrote: Try not to post full solutions to problems that are for classes. It was a practice exam, not for my course (I took it today so it was a bit late, felt like I did good!) but yeah I've made note to ask for people not to post entire answers if I ask for help before. Sorry in advance if it came out that way.
On October 15 2012 14:59 Blisse wrote:Show nested quote +On October 15 2012 14:35 Amnesty wrote:Derp posted too soon.. Anyway, i just made this last night for someone else so it seemed fitting to post it here since the disscussion about primes. Finds primes from 2-4 million well under a second. + Show Spoiler + #include <vector> #include <iostream> #include <algorithm> #include <iomanip> #include <ctime> #include <chrono> #include <ppl.h> #include <concurrent_vector.h> int main() { std::chrono::time_point<std::chrono::system_clock> TimeStart; std::chrono::time_point<std::chrono::system_clock> TimeEnd;
concurrency::concurrent_vector<int> primes; primes.push_back(2);
TimeStart = std::chrono::system_clock::now();
int Start = 3; int Stop = 4000000; int Step = 2;
// Comment out the multi-threaded version and uncomment the single threaded version to see the difference /// Multi-Threaded version Concurrency::parallel_for(Start,Stop, Step, [&primes](int n) { auto prime = true; int stop = sqrt(n);
for(auto j=2;j<stop;j++) { if(n%j==0) { prime = false; break; } } if(prime) primes.push_back(n); });
TimeEnd = std::chrono::system_clock::now(); auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(TimeEnd-TimeStart).count(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(TimeEnd-TimeStart).count(); std::cout << "Milliseconds : "<< millis << std::endl; std::cout << "Seconds : "<< seconds << std::endl; return 0; }
If this actually runs in less than a second, whoa, nice! I will save this somewhere XD Show nested quote +On October 15 2012 14:49 mmp wrote: Try not to post full solutions to problems that are for classes. He said it was for midterm studying so I thought it was okay.
I guess it could be that I'm lying and perhaps we can't go on trust but I like to think that we're acting in some form of mutual trust that we can rely that we're not cheating. For instance why would I cheat to get 10% mark on my end of the year but have no idea what I'm doing on my 60% final.
I can see his concern though, but I was definitely just studying and thank you by the way.
|
On October 16 2012 10:31 white_horse wrote:I think this is better for (int i = b; i <= a; i++) { for (int j = 2; j <= sqrt(i); j++) { if ((i%j != 0) && (i%2 != 0)) { cout << i << " is prime" << endl; } } }
The program keeps outputting 9 and 15 as prime numbers. I can understand why they are both outputted (they both satisfy the conditions in the if statement) but I don't know how to check that they are not prime.
Okay, so walk through it for 9:
for (int j = 2; j <= 3; j++) { if ((9 % j != 0) && (9 % 2 != 0)) { ... 9 is prime } }
j = 2: 9 % 2 != 0, 9 % 2 != 0, so it's prime j = 3: 9 % 3 == 0, 9 % 2 != 0, so it's not prime
What went wrong?
Similarly, for 81, I bet it outputs "81 is prime" ... once, twice... two times, when 81 isn't prime at all!
|
1019 Posts
well the program starts with 2, which screws up the whole thing, making 9 satisfy all the conditions so that its a "prime" number. If the program started with 3, everything would be ok.
|
On October 16 2012 10:31 white_horse wrote:I think this is better for (int i = b; i <= a; i++) { for (int j = 2; j <= sqrt(i); j++) { if ((i%j != 0) && (i%2 != 0)) { cout << i << " is prime" << endl; } } }
The program keeps outputting 9 and 15 as prime numbers. I can understand why they are both outputted (they both satisfy the conditions in the if statement) but I don't know how to check that they are not prime.
Well you are saying in that if condition that if there is a remainder for i % j for ANY value of j and its not an even number, it is prime. Whereas, it should only be counted as prime if it meets that condition for EVERY value of j in the inner for loop. I hope you see what I mean. You could create a boolean/integer variable called isprime that you set to true before the beginning of the inner for loop. Then if anywhere in that for loop (i%j) divides evenly (with a remainder of 0) set isprime to false, and early exit the loop. Then after the inner for loop you can see if isprime is still true or not. If it is, print prime, otherwise print not prime.
|
On October 16 2012 10:54 white_horse wrote: well the program starts with 2, which screws up the whole thing, making 9 satisfy all the conditions so that its a "prime" number. If the program started with 3, everything would be ok. That's fine for 9, but not 81. There is a flaw in your solution that can only be fixed by revising your solution strategy.
See JeanLuc's comment.
|
On October 16 2012 11:00 JeanLuc wrote:Show nested quote +On October 16 2012 10:31 white_horse wrote:I think this is better for (int i = b; i <= a; i++) { for (int j = 2; j <= sqrt(i); j++) { if ((i%j != 0) && (i%2 != 0)) { cout << i << " is prime" << endl; } } }
The program keeps outputting 9 and 15 as prime numbers. I can understand why they are both outputted (they both satisfy the conditions in the if statement) but I don't know how to check that they are not prime. Well you are saying in that if condition that if there is a remainder for i % j for ANY value of j and its not an even number, it is prime. Whereas, it should only be counted as prime if it meets that condition for EVERY value of j in the inner for loop. I hope you see what I mean. You could create a boolean/integer variable called isprime that you set to true before the beginning of the inner for loop. Then if anywhere in that for loop (i%j) divides evenly (with a remainder of 0) set isprime to false, and early exit the loop. Then after the inner for loop you can see if isprime is still true or not. If it is, print prime, otherwise print not prime. If you don't like 'break' statements, you can also write an isprime? function that returns false early in the loop as soon as it knows the number is not a prime. So in the case of 9, you don't know that 9 isn't a prime until you get to j = 3, because 3 divides 9. As soon as you see this, you can stop iterating.
|
On October 15 2012 10:56 white_horse wrote:Ok guys I have this project where if I input two numbers anywhere between 4 and 1 million, the program outputs all the prime numbers between the two. Well I got close to it but the program outputs but its really weird still....can you guys help me...... The professor talked about using square root function but I have no idea how. Here is the computational part:
a is lower limit and b is upper limit.
for (int i = a; i <= b; i++) { for (int j = 2; j*j <= i; j++) { if (i%2 != 0) { cout << i << " is prime" << endl; } }
Try thinking about how Prime Numbers work--what are their qualities? Besides two, they are never even, and they are only divisible by themselves and one. That's going to be the premise of your loop.
The other interesting quality of prime numbers in programming is that generally, the only real way to determine them is to just grind it out--you have to do it iteratively.
So try something like this:
for (int i = A; i <= B; i++) { boolean isPrime = true; for (int k = 4; k < i; k++) { if (k % i == 0) { isPrime = false; break; } } if (isPrime == true) { cout << i << " is prime" << endl; } }
What happens here is that "i" starts at A and iterates upward towards B. For each i, iterate from A to i (through k) and mod i. If k % i is ever 0, it means that k divides evenly into i, which means that i is not prime. When you exit the second loop, check to see if the number is still considered prime--if it wasn't prime it won't be. When you begin the loop again this check is reset back to true.
Note that you terminate the loop when k is equal to i, you don't want to do k % i when k == i, because if k == i and isPrime is still true then...hey, it's prime.
I recently had to do something similar when applying for me job, not quite this simple but, similar.
|
On October 16 2012 11:10 mmp wrote:Show nested quote +On October 16 2012 11:00 JeanLuc wrote:On October 16 2012 10:31 white_horse wrote:I think this is better for (int i = b; i <= a; i++) { for (int j = 2; j <= sqrt(i); j++) { if ((i%j != 0) && (i%2 != 0)) { cout << i << " is prime" << endl; } } }
The program keeps outputting 9 and 15 as prime numbers. I can understand why they are both outputted (they both satisfy the conditions in the if statement) but I don't know how to check that they are not prime. Well you are saying in that if condition that if there is a remainder for i % j for ANY value of j and its not an even number, it is prime. Whereas, it should only be counted as prime if it meets that condition for EVERY value of j in the inner for loop. I hope you see what I mean. You could create a boolean/integer variable called isprime that you set to true before the beginning of the inner for loop. Then if anywhere in that for loop (i%j) divides evenly (with a remainder of 0) set isprime to false, and early exit the loop. Then after the inner for loop you can see if isprime is still true or not. If it is, print prime, otherwise print not prime. If you don't like 'break' statements, you can also write an isprime? function that returns false early in the loop as soon as it knows the number is not a prime. So in the case of 9, you don't know that 9 isn't a prime until you get to j = 3, because 3 divides 9. As soon as you see this, you can stop iterating.
This is true, I would personally put a break in my loop to immediately terminate the second loop in the if statement. I knew I left something out.
|
On October 16 2012 10:31 white_horse wrote:I think this is better for (int i = b; i <= a; i++) { for (int j = 2; j <= sqrt(i); j++) { if ((i%j != 0) && (i%2 != 0)) { cout << i << " is prime" << endl; } } }
Look up the Sieve of Eratosthenes
This is perfect for what you want
|
On October 16 2012 15:08 frogmelter wrote:Show nested quote +On October 16 2012 10:31 white_horse wrote:I think this is better for (int i = b; i <= a; i++) { for (int j = 2; j <= sqrt(i); j++) { if ((i%j != 0) && (i%2 != 0)) { cout << i << " is prime" << endl; } } }
Look up the Sieve of Eratosthenes This is perfect for what you want
I don't agree, it would be overkill and make the solution more complex than neccessary. The simple brute-force method is more than enough for this case considering the highest number that can be entered is just 1 million.
|
On October 16 2012 15:30 Morfildur wrote:Show nested quote +On October 16 2012 15:08 frogmelter wrote:On October 16 2012 10:31 white_horse wrote:I think this is better for (int i = b; i <= a; i++) { for (int j = 2; j <= sqrt(i); j++) { if ((i%j != 0) && (i%2 != 0)) { cout << i << " is prime" << endl; } } }
Look up the Sieve of Eratosthenes This is perfect for what you want I don't agree, it would be overkill and make the solution more complex than neccessary. The simple brute-force method is more than enough for this case considering the highest number that can be entered is just 1 million.
Yes but the initial problem was (if I understood right) printing all prime numbers in a range. In that case printing all primes in range 2..1mil would actually take too much time with the brute force approach.
|
On October 16 2012 17:49 rethos wrote:Show nested quote +On October 16 2012 15:30 Morfildur wrote:On October 16 2012 15:08 frogmelter wrote:On October 16 2012 10:31 white_horse wrote:I think this is better for (int i = b; i <= a; i++) { for (int j = 2; j <= sqrt(i); j++) { if ((i%j != 0) && (i%2 != 0)) { cout << i << " is prime" << endl; } } }
Look up the Sieve of Eratosthenes This is perfect for what you want I don't agree, it would be overkill and make the solution more complex than neccessary. The simple brute-force method is more than enough for this case considering the highest number that can be entered is just 1 million. Yes but the initial problem was (if I understood right) printing all prime numbers in a range. In that case printing all primes in range 2..1mil would actually take too much time with the brute force approach. It's fine. It takes a couple of seconds if you use sqrt, a couple of minutes otherwise.
|
On October 16 2012 17:49 rethos wrote:Show nested quote +On October 16 2012 15:30 Morfildur wrote:On October 16 2012 15:08 frogmelter wrote:On October 16 2012 10:31 white_horse wrote:I think this is better for (int i = b; i <= a; i++) { for (int j = 2; j <= sqrt(i); j++) { if ((i%j != 0) && (i%2 != 0)) { cout << i << " is prime" << endl; } } }
Look up the Sieve of Eratosthenes This is perfect for what you want I don't agree, it would be overkill and make the solution more complex than neccessary. The simple brute-force method is more than enough for this case considering the highest number that can be entered is just 1 million. Yes but the initial problem was (if I understood right) printing all prime numbers in a range. In that case printing all primes in range 2..1mil would actually take too much time with the brute force approach.
Not really, slight optimizations can be made to drastically improve performance. I made slight errors in my loop, for instance--it shouldn't iterate through every number between 4 and 1 million, it should iterate through every odd number from 5 to 1 million (4 isn't a prime number), cutting the number of iterations in half (even numbers aren't prime except for 2). Breaking the moment you see a lack of primeness also improves performance of the brute force method.
If your computer isn't from the 60's, it can do basic arithmetic pretty quickly. In fact, the only numbers that may take awhile to print are numbers that are actually prime themselves, a lack of primeness will be determined very, very shortly if the number isn't prime.
for (int i = A; i <= B; i++) { boolean isPrime = true; for (int k = 4; k < i; k+2) { if (k % i == 0) { isPrime = false; break; } } if (isPrime == true) { cout << i << " is prime" << endl; } }
We're talking about a freshman or sophomore level program here, this thing doesn't have to be optimized or operate at log(n) speed. I don't think he's being asked to cache all the prime numbers between 4 and 1 million and then print out values greater than i. On the flip side if you want to be awesome you could execute the loop to store all the prime numbers between 4-1,000,000 in an array (sorted least to greatest) and then given a number N perform a binary search and print out all the values greater than N. That would be logN. And boss.
Programming is awesome.
|
+ Show Spoiler +Don't even need to do a binary search, representing the primes as a bitset of size 1,000,001 can print in N time. :D
In any case, generating the prime numbers is the only hard part. Shouldn't just give him the answer though, so I would hide that code.
|
On October 17 2012 09:26 Blisse wrote: Don't even need to do a binary search, representing the primes as a bitset of size 1,000,001 can print in N time. :D
In any case, generating the prime numbers is the only hard part. Shouldn't just give him the answer though, so I would hide that code.
N time is pretty undesirable.
|
Sorry, I thought O(n) was better than O(logn) for some reason.
Oh, confused with O(nlogn). ~__~
|
For some reason my school decided to switch languages for my intro CS course, so instead of learning C++ we're starting out with Python. Then later on in the second semester of the intro course we get into C++ and Java. Any idea why they would do that? I would think that just jumping into C++ and Java would seem more beneficial. My father's friend is a software Architect of some sort and when I told him that I wanted to get into the technical side of things, I should devote time to learning Java @_@.
I really wish that I settled down and decided to go with CS as my minor right from the get go because writing up a program to solve stats or any homework that has to deal with math would've made life so much easier...
|
for the prime generation, efficient prime number generation algorithms can be used. Just look at this website. It will give you a good understanding of what and how you should do to generate prime numbers efficiently (it takes you step by step). It's a very guide to understanding where you can make adjustments in your algorithm to speed up the process.
I didn't really read what he was asking, but all I saw was that he wanted to generate primes, so I thought of that (sorry if off-topic).
|
On October 18 2012 00:36 Snuggles wrote: For some reason my school decided to switch languages for my intro CS course, so instead of learning C++ we're starting out with Python. Then later on in the second semester of the intro course we get into C++ and Java. Any idea why they would do that? I would think that just jumping into C++ and Java would seem more beneficial. My father's friend is a software Architect of some sort and when I told him that I wanted to get into the technical side of things, I should devote time to learning Java @_@.
I really wish that I settled down and decided to go with CS as my minor right from the get go because writing up a program to solve stats or any homework that has to deal with math would've made life so much easier...
Python is far more friendly to new programmers than Java and C++. Among other things, you can emphasize good programming fundamentals in a simpler language like Python without having to also get bogged down in too many unnecessary details like with Java and C++.
|
|
|
|