Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

plotting the number of actions for ex i=i+1 ( action), pgd=n/i ( action), pgd=n(action)

조회 수: 1 (최근 30일)
ime sem
ime sem 2013년 11월 9일
마감: MATLAB Answer Bot 2021년 8월 20일
function pgd = entier(n)
i = 2;
while in/2 & mod(n,i)~-0
i = i+1;
end
if mod(n,i)==0
pgd = n/i;
else
pgd = n;
end
end
  댓글 수: 1
Roger Stafford
Roger Stafford 2014년 1월 22일
In this example you are seeking the smallest divisor of n which is greater than one. However, it isn't necessary to go all the way to n/2. You can stop at sqrt(n) because if there isn't a divisor by that point, you won't find any others less than n. (Of course none of this has anything to do with counting "actions".)

답변 (1개)

AJ von Alt
AJ von Alt 2014년 1월 21일
You can create a variable to count the number of actions taken and increment it every time an action is take. Have your function return that variable and store it for later plotting.
function [pgd , nActions] = entier(n)
nActions = 0;
i = 2;
while i<=n/2 && mod(n,i)~=0
i = i+1;
nActions = nActions + 1;
end
if mod(n,i)==0
pgd = n/i;
nActions = nActions + 1;
else
pgd = n;
nActions = nActions + 1;
end
end
  댓글 수: 2
Walter Roberson
Walter Roberson 2014년 1월 21일
The line
while i<=n/2 && mod(n,i)~=0
requires at least two actions, one for the division and one for the mod() calculation. I would also suggest that if assignment is to be treated as an action, that comparison would have to be an action as well, remembering the && comparison should also be an action. Then one needs to take into account that && "short circuits" and so the mod() and comparison to 0 would not require actions if i<=n/2 is false.
AJ von Alt
AJ von Alt 2014년 1월 22일
Good catch! If the user wants to count the modulo and logical operations in addition to the ones listed in the title, some rework would be in order. Ime used & instead of && in his original implementation, so if he sticks with elementwise AND rather than my short circuit AND, he at least won't have to worry about short circuiting.

제품

Community Treasure Hunt

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

Start Hunting!

Translated by