How to Solve an equation using if statements?

I am trying to solve this equation. I know I have to write if statements but I forgot how to do it. The equation is : a^4+b^2+c^2=2014 and a+b+c=?.
I know I have to set each variable up an interval.
Thank you.

댓글 수: 3

I solved my own problem.
for a = 0:1:100
a4 = a^4;
for b = 0:1:100
b2 = b^2;
for c = 0:1:100
c2 = c^2;
if a4 + b2 + c2 == 2014
break
end
end
if a4 + b2 + c2 == 2014
break
end
end
if a4 + b2 + c2 == 2014
break
end
end
disp('A4 + B2 + C2 =');
disp(a4 + b2 + c2);
disp('A =');
disp(a);
disp('B =');
disp(b);
disp('C =');
disp(c);
disp('A + B + C =');
disp(a + b + c);
if true
% code
end
John D'Errico
John D'Errico 2015년 7월 11일
편집: John D'Errico 2015년 7월 11일
WAY more work than is necessary. For example, do you really need to look as far as 100 for a? What is 100^4? Is it considerably larger than 2014?
So is there any reason to look further out for a than floor(nthroot(2014,4))==6?
Likewise, how far out did you need to look at b and c?
Robert
Robert 2016년 6월 18일
I wasn't focused on optimizing initially when I wrote it. However, I can see your point. 100 is way too high to start.

댓글을 달려면 로그인하십시오.

 채택된 답변

John D'Errico
John D'Errico 2016년 6월 18일
편집: John D'Errico 2016년 6월 18일

1 개 추천

Has nobody ever answered this? So
sqrt(2014)
ans =
44.878
nthroot(2014,4)
ans =
6.6991
A needs never go past 6. b needs never go past 44. In fact, since b and c are symmetrical, assuming you wish to find unique solutions, just assume that b>=c. Therefore, you can limit c to vary from 0 to b. Yes, this does find all unique solutions, since if you had a solution where b was less than c, then just swap them, and you have another solution, with b>=c.
So the above scheme would work using loops.
A simple non-looping solution might look like this:
target = 2014;
amax = floor(nthroot(target,4));
bmax = sqrt(target);
cmax = bmax;
[aa,bb,cc] = ndgrid(0:amax,0:bmax,0:cmax);
ind = find((aa.^4 + bb.^2 + cc.^2) == target);
[aa(ind),bb(ind),cc(ind)]
ans =
3 42 13
3 13 42
As you can see, there are two solutions, symmetrical in b and c. As well, the ndgrid solution is the way one would normally solve it in MATLAB, since it does not force you to set up lots of loops, tests, breaks,etc.

댓글 수: 1

Robert
Robert 2016년 6월 18일
I like the way to not have to use multiple loops. It seems like the more code you have the more change of error can happen.
Which is why I keep having problems with it now? Maybe you can help me out now? See link below.
I have found that isn't running through the loops more than once. Then I can't figure out how to assign T(1) has a not a set number.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Programming에 대해 자세히 알아보기

제품

질문:

2015년 7월 10일

댓글:

2016년 6월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by