Why this function infinity loop
조회 수: 6 (최근 30일)
이전 댓글 표시
%It give an integer x which contains d digits, find the value of n (n > 1) such that
%the last d digits of x^n is equal to x. Example x=2 so n=5 because 2^5=32 and last
%digits of 32 is 2
%So why this take infinity loop
function n = bigNumRepeat(x)
d = length(num2str(x))
y=2
n=2
while 1
y = y*x
y = num2str(y)
y = str2num(y(end - d + 1:end))
if y==x
break
end
n=n+1
end
end
댓글 수: 0
답변 (2개)
John D'Errico
2021년 5월 7일
Because if your powers grow larger than 2^53-1 (i.e., flintmax), the number is no longer expressable exactly as an integer. All of those operations with str2num will produce garbage at some point. You CANNOT do this using doubles if the number grows too large.
댓글 수: 5
Walter Roberson
2021년 5월 8일
x = randi([11 99])
d = length(num2str(x))
y = x;
n = 1;
flag = true;
modulus = 10^d;
while flag && n <= 1000
n = n + 1;
y = mod(x*y,modulus);
flag = y ~= x;
end
if flag
fprintf('not found in 1000 iterations\n')
else
n
end
Note that x is not relatively prime with 10^d then there might not be a solution.
Walter Roberson
2021년 5월 7일
편집: Walter Roberson
2021년 5월 7일
y=2
y = y*x
That does not give you x^n, it gives you 2 * x^n . You should initialize y = 1
See also https://www.mathworks.com/matlabcentral/fileexchange/932-big-x-y-modulo-function and see the symbolic powermod() function
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!