Help with infinite while loop

I need to create a simple script that take a number, checks if it odd or even. If it's even: divide by two, if it's odd: multiply by 3 add 1. The script is supposed to repeat this check and calculation until the output reaches a value of one. I've tried the following while loop which calculates the first value but then infinity spits out this same value. Thanks in advance!
clear
disp('Please input student number')
ID = input('SI#: ');
if mod(ID,2) == 0
out = ID/2
else out = ID.*3+1
end
while out > 1
if mod(ID,2) == 0
out = ID/2
else out = ID.*3+1
end
end

댓글 수: 6

Matt J
Matt J 2012년 11월 24일
It doesn't seem easy to prove that this will eventually converge to 1. Is it a well-known result from somewhere?
Matt Fig
Matt Fig 2012년 11월 24일
@Matt J - AFAIK, it is not proven. But it has been extensively tested and never found to fail. Look up Collatz conjecture.
Azzi Abdelmalek
Azzi Abdelmalek 2012년 11월 24일
Tested in a loop for k=1:10^6 with randi, never fail.
Walter Roberson
Walter Roberson 2012년 11월 24일
For example, my BOINC client just finished testing 8E12 numbers starting from 2377489401671993502056 without finding any counter-example.
Matt J
Matt J 2012년 11월 24일
OK. Glad I didn't spend my day trying to prove it :)
Jan
Jan 2012년 11월 25일
편집: Jan 2012년 11월 25일
It is not proved. See http://en.wikipedia.org/wiki/Collatz_conjecture. You can earn 500$ and the Fields medal when you prove it, but this would conflict with the term " algorithmically undecidable".

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

답변 (3개)

Matt Fig
Matt Fig 2012년 11월 24일
편집: Matt Fig 2012년 11월 24일

0 개 추천

The problem is that ID never changes in your loop so you are just doing the same thing over and over. Change all 'out' variables to 'ID' and your code should work fine.
Devan
Devan 2012년 11월 24일

0 개 추천

thanks!
Jan
Jan 2012년 11월 25일
편집: Jan 2012년 11월 25일

0 개 추천

It is a good idea to ask Google, in this case for "3N+1 Wiki". You find explanations, theorems, algorithms and visualizations, ... Enough material to solve the homework.

카테고리

도움말 센터File Exchange에서 Call C++ from MATLAB에 대해 자세히 알아보기

태그

질문:

2012년 11월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by