Hello guys, I am new to MatLab and I made a code to get the GCD of a number but I suspect it could bbe better. Any tips?
This topic has been permanently closed and transferred to MATLAB Answers.
n= input('Escolhe um número inteiro postivo. ')
primo=true;
i=2;
while i<n
if mod(n,i)==0;
primo=false;
end
i= i+1;
end
if primo && n>1;
disp('É primo')
else
disp('Não é primo')
end
anterior= n-1;
while true
primo=true;
i=2;
while i< anterior
if mod(anterior,i)==0;
primo= false;
end
i= i+1;
end
if primo && anterior>1;
end
anterior= anterior-1;
end
disp(anterior)
seguinte= n+1;
while true;
primo= true;
i=2;
while i<seguinte;
if mod(seguinte,i)==0;
primo=false;
end
i=i+1;
end
if primo && seguinte>1;
end
seguinte= seguinte+1;
end
disp(seguinte)
2 Comments
Time Descending@Pedro: you should delete this discussion and post your question here (click "Ask"):
function g = myGCD(a, b)
a = abs(a);
b = abs(b);
while b ~= 0
temp = b;
b = mod(a, b);
a = temp;
end
g = a;
end
why it is better
- Time complexity: O(log(min(a,b)))
- No unnecessary loops
- Handles negative numbers
- Works for any integer inputs
Comments have been disabled.