Write a Matlab script that asks for an integer (n) and then computes the following based on the value of the integer:

조회 수: 35 (최근 30일)
While the value of n is greater than 1, replace the integer with half of its value (n/2) if the integer is even. Otherwise, replace the integer with three times its value, plus 1 (3*n + 1).
Print the sequence that results.
Example: if n=10 then the sequence will be 10, 5, 16, 8, 4, 2, 1
  댓글 수: 2
Ingrid
Ingrid 2015년 5월 7일
when posting homework questions you should at least also show the code that you have tried so far and indicate where you got stuck
Purushottama Rao
Purushottama Rao 2015년 5월 7일
As i understood from the question, you would like to input an interger say 10, and you would like to generate a sequence. Is the sequence should consider 1 to 10 numbers for the above said arithematics. Then in that case for a given integer say 10, the sequence conatins 10 elements? is that what you want to do?

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

답변 (2개)

Ingrid
Ingrid 2015년 5월 7일
편집: Ingrid 2015년 5월 7일
prompt = 'Give an integer value? ';
n = input(prompt);
% check if integer number is provided
if ~(abs(round(n)-n) < eps)
errordlg(' The number provided is not an integer');
else
while n > 1
if floor(n/2) == n/2
%number is even
n = n/2;
else
%number is odd
n = 3*n+1;
end
disp(n)
end
end
this took about 1 minute so should not have been too difficult to solve yourself
  댓글 수: 1
Guillaume
Guillaume 2015년 5월 7일
"this took about 1 minute so should not have been too difficult to solve yourself", so it would be best no to give away the whole solution without seeing at least some sort of attempt by the OP.

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


Purushottama Rao
Purushottama Rao 2015년 5월 7일
k=input('enter the data')
a=1:k;
disp('before manipulations')
disp(a)
for n=1:length(a)
if (a(n)>1&&mod(a(n),2)==0)
a(n)=0.5*a(n);
elseif (a(n)>1 && mod(a(n),2)==1)
a(n)=3*a(n)+1;
end
end
enter the data 10
k =
10
before manipulations 1 2 3 4 5 6 7 8 9 10
after manipulations 1 1 10 2 16 3 22 4 28 5 disp('after manipulations') disp(a)
  댓글 수: 5
Purushottama Rao
Purushottama Rao 2015년 5월 7일
I think the way the question asked is somewhat confusing to me. Looking at the exapmle if the input is 10, then how can he have a sequence of no.. Acoordig to your code it must be a single value 5. But it has been indiated that the sequence is expected...
Guillaume
Guillaume 2015년 5월 7일
I thought that was pretty clear. The first element of the sequence is the input number, the next element is either:
  • half the previous element, if it is even
  • 1 plus 3 times the previous element, if it is odd and greater than one
  • the end of the sequence, if it is 1.

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

카테고리

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