Writing a script for Goldbach's Conjecture
17 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Rik
2022-3-19
编辑:Rik
2022-3-19
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.
更多回答(1 个)
John D'Errico
2022-3-19
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 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!