"FOR" loop

조회 수: 22 (최근 30일)
Juan Alvarez
Juan Alvarez 2011년 12월 4일
댓글: Dinesh Kannan Natarajan 2021년 4월 28일
I have to find the prime numbers from that lead up to 100 and then use the 'for' function to multiply adjecent prime numbers: example:
first prime numbers
2 3 5 7
and i need the 'for' to do the following with the prime numbers
2*3 3*5 5*7 etc...HELP PLEASE
  댓글 수: 1
Dinesh Kannan Natarajan
Dinesh Kannan Natarajan 2021년 4월 28일
% to Generate prime number between the intervals
clear;
clc;
m=input('provide the required start point of prime number: ');
n=input('provide the required end point of prime number: ');
if n<=0
pr='Error';
disp('ERROR: Input argument must be a positive integer')
elseif round(n)~=n||round(m)~=m
pr='Error';
disp('ERROR: Input argument must be positive integer')
elseif n <= m
pr='Error';
disp('ERROR: end point must be greater than start point')
else
k=1;
for i=m:n
c=0;
for j=2:i-1
if rem(i,j)==0
c=1;
break
end
end
if c==0
pr(k)=i;
k=k+1;
end
end
end
pr

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

답변 (4개)

Junaid
Junaid 2011년 12월 4일
let say your prime vector is P;
p=primes(100);
a = zeros(1,length(p)-1);
for i=1:length(p)-1
a(i) = p(i) * p(i+1);
end
a
though you can do it also without loop but you asked for a loop so it is loop solution.
  댓글 수: 1
Juan Alvarez
Juan Alvarez 2011년 12월 4일
im sorry but this did not help...
i am at here so far
k=primes(100)
then it list the primes but i cant figure out how to use the for loop at all

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


Junaid
Junaid 2011년 12월 4일
p=primes(100);
A = zeros(1,length(p)-1);
for i=1:length(p)-1
A(i) = p(i) * p(i+1);
end
A
just copy and paste the code, answers is in vector (A) try this, do let us know if it is what you wanted to do.
  댓글 수: 1
Juan Alvarez
Juan Alvarez 2011년 12월 6일
This helped a lot!! thanks!

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


Sean de Wolski
Sean de Wolski 2011년 12월 6일
Loop sure seems like overkill
x = primes(100);
x1p1 = x(1:end-1).*x(2:end);

Andrei Bobrov
Andrei Bobrov 2011년 12월 4일
a = 1:100;
yourprime = a(a - sum(rem(triu(bsxfun(@rdivide,a,a.')),1)>0)<=2);
out = prod(yourprime(bsxfun(@plus,1:numel(yourprime)-1,(0:1)')))
  댓글 수: 1
Paulo Silva
Paulo Silva 2011년 12월 6일
It takes a while for me to understand your code, nicely done

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

카테고리

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