matlab loops break and continue commands

조회 수: 5 (최근 30일)
Alinetin
Alinetin 2020년 4월 9일
댓글: Walter Roberson 2020년 4월 9일
In number theory, a semi-perfect number is a positive integer number that is equal to the sum of its largest three positive divisors, excluding the number itself. For example; 18 is a semiperfect number, the positive divisors of this number are 1,2,3,6,9,18, and the sum of the three largest integer divisors (excluding the number itself) is 3 + 6 + 9 = 18. Write a MATLAB program that checks whether a given number is semi-perfect number.
  댓글 수: 2
Ameer Hamza
Ameer Hamza 2020년 4월 9일
This seems like a homework question. What have you already tried?
mehmet kiraccakali
mehmet kiraccakali 2020년 4월 9일
편집: mehmet kiraccakali 2020년 4월 9일
n=input('Enter a number ');
sum=0;
for i=n-1:-1:1
if mod(n,i)==0
sum=sum+i;
end
end
if sum==n
fprintf('%d is a semi-perfect number \n',n);
else
fprintf('%d is not a semi-perfect number \n',n);
end
I couldn't solve this question either, I tried to make the solution above. but i don't know how to find the three biggest divisors.

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

답변 (1개)

Peng Li
Peng Li 2020년 4월 9일
You are almost there. Just need a seperate counter that force the loop to break if it accumulates to 3.
n = input('Enter a number ');
sum = 0;
ind = 0;
for i = n-1:-1:1
if mod(n, i) == 0
sum = sum + i;
ind = ind + 1;
if ind == 3
break;
end
end
end
if sum == n
fprintf('%d is a semi-perfect number \n',n);
else
fprintf('%d is not a semi-perfect number \n',n);
end
  댓글 수: 7
Ayberk Dönmez
Ayberk Dönmez 2020년 4월 9일
thank you so much
Walter Roberson
Walter Roberson 2020년 4월 9일
sum of its largest three positive divisors
That is why 3 was chosen to compare against.
ind is being used to count how many factors have been found so far.

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

카테고리

Help CenterFile Exchange에서 Numerical Integration and Differentiation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by