Generating a rather intricate loop with inequalities

2 次查看(过去 30 天)
I have to create a code that, given positive integers m and n, calculates integers k and r such that m=kn+r and r<n by successively subtracting n first from m and then from m-n and then from m-2n and so on in a loop. as many times as possible without the remainder r=m-kn becoming negative, and which finally prints k and r on the screen.
This seems a little confusing, since r and k are not calculated readily, since we have an inequality at r<n, and not an equality. If it was r=n, we would have no problem and could proceed to the loop.
My code is as given, however, it stops since r<n and cannot be calculated. Any ideas how to solve this? Thanks
m=1
n=2
% Initialize the starting number
number = m;
% Loop
while number <= m-n*n
disp(number);
number = number-n; % Subtract n from m
end
if r==m-kn;
end
if r<n;
end

采纳的回答

Hassaan
Hassaan 2024-1-18
编辑:Hassaan 2024-1-18
Your current code does not correctly calculate k and r. Here's an adjusted version:
m = 1; % Example values for m
n = 2; % Example values for n
% Initialize k and r
k = 0;
r = m;
% Loop to find k and r
while r >= n
r = r - n; % Subtract n from r
k = k + 1; % Increase k by 1 for each subtraction
end
% Display the results
fprintf('k: %d, r: %d\n', k, r);
k: 0, r: 1
This code initializes k and r, then uses a loop to subtract n from r until r is less than n. Each subtraction increases k by 1. After the loop, k and r will satisfy the conditions m = kn + r and r < n.
-----------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
Professional Interests
  • Technical Services and Consulting
  • Embedded Systems | Firmware Developement | Simulations
  • Electrical and Electronics Engineering
It's important to note that the advice and code are based on limited information and meant for educational purposes. Users should verify and adapt the code to their specific needs, ensuring compatibility and adherence to ethical standards.
Feel free to contact me.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

标签

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by