필터 지우기
필터 지우기

Stop value in loop for repeating

조회 수: 2 (최근 30일)
Pallav Patel
Pallav Patel 2020년 3월 12일
댓글: James Tursa 2020년 3월 12일
clc;
clear;
close all;
rng('shuffle');
myint = randi([4,100]);
while mod(myint,2) ~= 0
myint = randi([4,100]);
end
fprintf('%d is the sum of these prime numbers\n',myint);
myprime = primes(myint);
mylength = ceil(length(myprime)/2);
for i=1:length(myprime)
for k=1:length(myprime)
if(myprime(i)+myprime(k)== myint)
num1 = myprime(i);
num2 = myprime(k);
fprintf('%d = %d + %d \n',myint,num1,num2)
end
end
end
i am trying to create the goldbach conjecture but I do not want the prime numbers that have already been listed to repeat. eg 7+5 and 5+7.

채택된 답변

James Tursa
James Tursa 2020년 3월 12일
Not sure if you need the numbers to be different or not. Either this:
for k=i:length(myprime)
or this
for k=i+1:length(myprime)
  댓글 수: 2
Pallav Patel
Pallav Patel 2020년 3월 12일
Thank you james. Both of them work perfectly. Could you please elaborate more as I am trying to understand the code
James Tursa
James Tursa 2020년 3월 12일
This simply forces myprime(k) to be greater than (or equal to depending on which code you use) the value of myprime(i). So you will never get both the 5 + 7 and the 7 + 5 choices.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by