Loop is killing proccesor.
조회 수: 1 (최근 30일)
이전 댓글 표시
I am running the code below where I am trying to create a matrix for all the products of x digit numbers. Works fine for 1 and 2 digit numbers but three kills it. I have taken the semi colon off of 'z' and also 'x' in the first if statement so I can watch the output. For the first hundred loops (999 to 900) it is fast then gets progressively slower. The same number of tasks are being done each loop, so where my problem must be in loading the answers onto the end of my matrix 'NumLine'. Is this my problem?
function palout =paladin(numDig)
%NumLine = ((10^(numDig-1)^2):((10^numDig)-1)^2);
xMax = 10^numDig-1; %Upper bound
x = xMax;
y = x;
z = 10^(numDig-1) %Lowwer bound
NumLine = [];
while x >= z
NumLine(end+1) = x*y;
if y == z
x = x-1
y = xMax;
else
y = y-1;
end
end
palout = NumLine;
댓글 수: 0
채택된 답변
추가 답변 (1개)
bym
2011년 10월 29일
I was going to comment but I thought my reply might be better an answer. You can preallocate as long as you know apriori what the size you are expecting. If you don't know the size, the allocate in 'reasonable' chunks.
I take it from your code, you are trying to solve Project Euler #4 which ask for the largest palindrome for a product of two 3 digit numbers. So without preallocation generate the first chunk of data by using
a = (999:-1:900)'*(999:-1:900);
which gives you the first 10,000 products of two 3 digit numbers. You can search through these for the largest palindrome.
If you want to continue using loops, just allocate numbers in (100 x 100) blocks till you achieve your result. I think you will find you do not have to go beyond the range I have shown above
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!