Need help for Cody Problem 42409: Divisible by 7

6 ビュー (過去 30 日間)
Hi! I am new in Matlab programing. I try to learn this language through cody problem. But I couldn't solve this problem for a long time. It'll be a great help for me if you give me some solutions!
I have been trying this problem to solve for a several time but everytime it shows the same error. When I run this code in the Scratch Pad, I get the desirable result, but when i submit my code, it shows an error: "The server timed out while running and assessing your solution. Use the Run button to verify your code. If successful, submit again.If the error persists, contact the instructor.".
**For your information, in this problem I can not use direct functions to get the answer. I have to do everything manually. Please see the problem question first in the link below.
I am submitting my written code here and also the link of the Cody Probelm. Thanks in advance for your suggesitions!
x = num2str(n_str) - '0';
seven = [0 7 14 21 28 35 42 49 56 63 70 77 84 91 98];
l = length(x);
if l > 2
while l > 2
p = x(1:end-1);
p = num2str(p);
p(p == ' ') = [];
p = str2num(p);
s = p - x(end)*2;
x = num2str(s) - '0';
l = length(x);
end
else
s = str2num(n_str);
end
s
if any(seven(:) == s) == 1
tf = 1
else
tf = 0
end
Please tell me if there is anything wrong in my code or the arrangements.

採用された回答

Dyuman Joshi
Dyuman Joshi 2021 年 5 月 4 日
You are getting the error because your code took to long to process than the allowed time limit.
1 - The input is in the form of string so, use x = n_str-'0';
2 - You can get rid of the first set of if/else statements, and just use the while loop. Your code will work the same.
3 - You can improve the speed of your while loop by substituting statements which do the work quickly.
x=n_str-'0';
while length(x) > 2 %Instead of defining 'l' as a variable, directly use length(x).
p = polyval(x(1:end-1),10);
s = p - x(end)*2;
x = num2str(s) - '0';
end
%defining variable takes memory to be stored and needs memory to be calculated at every loop iteration
If you want to learn MATLAB, Cody is not the best place to do so. Cody is meant for practicing/applying the skills you learnt. I would suggest you start with MATLAB Onramp course.
  3 件のコメント
Nafees Ul Haque Akhand
Nafees Ul Haque Akhand 2021 年 5 月 4 日
Sure, I will try some other methods. Thanks for your help and sure will take the Onramp course you suggested.

サインインしてコメントする。

その他の回答 (0 件)

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by