Writing a script for Goldbach's Conjecture
23 views (last 30 days)
Show older comments
Theresia Dannbauer
on 19 Mar 2022
Commented: Theresia Dannbauer
on 19 Mar 2022
Hello Matlab Community,
I want to write a script that shows that all even integers between n = 4 and n = N (with N = 1000) can be represented as the sum of two primes, and use the function "assert" to confirm the claim.
This is what I've written so far, unfortunately the assertion fails:
n = 4; N=1000;
Even = n:2:N;
Number = Even(randperm(length(Even),1))
P = primes(N); P = P(P>=n);
Primenumbers = P(randperm(numel(P),2))
sum(Primenumbers)
assert(isequal(Number, sum(Primenumbers)))
Please no loops! I was told the functions "all" and "unique" might be useful. I read the documentation on both, but I am not sure how I can use them in this code!
I am very thankful for any tips!
0 Comments
Accepted Answer
Rik
on 19 Mar 2022
Edited: Rik
on 19 Mar 2022
I think the goal is to use implicit expansion to create an array with the sums of all primes. A bit like this:
A=[1 2 3 5];
B=A+(A.');
Now you have all the possible sums of two primes. How can you use this to compare it to your other list?
I think I would suggest ismember instead of unique.
More Answers (1)
John D'Errico
on 19 Mar 2022
Let me suggest you are starting from the wrong end?
Instead, start with all primes less than your target maximum, so 1000. Can you find them easily? (Hint: what does primes do?)
help primes
Can you now easily find the sum of all combinations of two of those primes? This is not that difficult, since there are only 168 primes less than 1000. (Hint: you could use meshgrid here.)
help meshgrid
In fact, you may even have learned an easier way to form an addition table. What does this do?
P = [2 3 5 7];
P'+P
Once you have the sum of ALL combinations of 2 primes, convert the result to a vector, and now can you now use unique? Actually, even easier is to use setdiff here. So find the difference between two sets of numbers, where one of those sets is composed of the even numbers 2:2:1000. If this last computation is empty, then ALL even integers had some way to be formed of exactly 2 primes.
Since this is homework, I truly hope that nobody writes the code for you. However, if you make a credible effort along the lines I just gave in detail, then show what you tried if you still have a problem. Out it in a comment to my answer. However, I might even bet you will be successful, IF you make an effort.
2 Comments
See Also
Categories
Find more on Animation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!