필터 지우기
필터 지우기

what are all possibilities for a,b,c to be 72?

조회 수: 6 (최근 30일)
Quinten Lodewijks
Quinten Lodewijks 2017년 3월 28일
댓글: Quinten Lodewijks 2017년 3월 29일
a = [0:1:20]; b = [0:1:20]; c = [0:1:20];
i want to know what all the possibilities are of the product of a*b*c to be 72
i tried with an if statement but this doesn't work.
  댓글 수: 7
Quinten Lodewijks
Quinten Lodewijks 2017년 3월 28일
and Tomas, how do i have to use that? do i have to put a,b,c before the code and execute the whole section or how do i need to use your code?
anyway thanks for replying!
Tomas Hipolito
Tomas Hipolito 2017년 3월 28일
You need to define a,b and c before the code. a, b and c vary from 0 to 20, right? In Matlab you define them as vectors as you did in your question. I didn't try the code, there is the possibility to have a syntax error. So it would be
a=[0:1:20];
b=[0:1:20];
c=[0:1:20];
and the rest of the code written above.
Tell me if it worked.

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

채택된 답변

Thorsten
Thorsten 2017년 3월 28일
편집: Thorsten 2017년 3월 28일
a = nchoosek(1:72, 3);
idx = prod(a, 2) == 72;
a(idx, :)
  댓글 수: 2
Quinten Lodewijks
Quinten Lodewijks 2017년 3월 28일
thanks!
Thorsten
Thorsten 2017년 3월 29일
I think that the following is correct:
a = [];
for i = 1:72, for j = 1:72, for k = 1:72,
if i*j*k == 72, a(end+1,:) = [i, j, k]; end
end, end, end

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

추가 답변 (1개)

Jan
Jan 2017년 3월 29일
편집: Jan 2017년 3월 29일
The allowed range is 1:20 for the 3 elements (ignoring the 0), not 1:72.
P = nchoosek(1:20, 3)
idx = prod(P, 2) == 72;
P(idx, :)
Or equivalently for Torsten's comment: for i = 1:20, ...
The loops can be stopped prematurely:
Result = [];
for i1 = 1:20
for i2 = 1:20
for i3 = 1:20,
p = i1 * i2 * i3;
if p == 72
Result(end+1, :) = [i1, i2, i3];
break; % Former products for larger i3 are > 72
elseif p > 72
break; % Former products for larger i3 are > 72 also
end
end
end
end
We know the prime factors of 72:
factor(72)
% 2 2 2 3 3
This means that we do not have to check values, which cannot be created by numbers, which cannot be build as a product of these values (and the 1):
Pool = [1, 2, 3, 4, 6, 8, 9, 12, 18];
Result = [];
for i1 = Pool
for i2 = Pool
for i3 = Pool
p = i1 * i2 * i3;
if p == 72
Result(end+1, :) = [i1, i2, i3];
break; % Former products for larger i3 are > 72
elseif p > 72
break; % Former products for larger i3 are > 72 also
end
end
end
end
  댓글 수: 1
Quinten Lodewijks
Quinten Lodewijks 2017년 3월 29일
Thank you so much! this solved the problem for me. The code was longer than I expected it to be haha

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by