Squares of all positive odd integers whose sum is greater than or equal to 3,000,000

조회 수: 2 (최근 30일)
I'm trying to create a program that calculates the squares of all positive odd integers whose sum is greater than or equal to 3,000,000. The problem is that I'm not given a specified number of terms to use and was wondering if there was any way to do this without just specifying the amount of terms by hand.
array = [];
sum = 0;
n = 0;
while sum <= 3000000
for i = 1:2:n+2
array(i) = i^2;
sum = sum + i^2;
end
n = n + 1;
end
I was trying something like this but i'm pretty sure my variable n is what's messing up the for loop from giving me the right increments.
  댓글 수: 5
Noah Sickels
Noah Sickels 2020년 9월 25일
It's not specified but i presummed it would start at 1 and go from there. He's not very specific on any of these projects which makes the actual program hard to complete in the way he desires.
Steven Lord
Steven Lord 2020년 9월 25일
First, you shouldn't use sum as a variable name. While that variable exists you won't be able to call the function named sum.
Second, there's no need for a for loop in this assignment. The while keyword is a looping construct. As the old folk song goes:
bottlesOfBeerOnTheWall = 99;
while bottlesOfBeerOnTheWall > 0
fprintf("%d bottles of beer on the wall\n", bottlesOfBeerOnTheWall)
fprintf("%d bottles of beer\n", bottlesOfBeerOnTheWall)
fprintf("You take one down\n");
bottlesOfBeerOnTheWall = bottlesOfBeerOnTheWall-1;
fprintf("You pass it around\n");
fprintf("%d bottles of beer on the wall\n\n", bottlesOfBeerOnTheWall)
end
This will execute the five fprintf statements and the one subtraction until the condition is no longer satisfied. I think you've already identified the equivalent of putting the bottles of beer on the wall and checking if there is any beer on the wall. What's the equivalent of taking the nth bottle of beer from the wall and passing it around for your assignment?

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

답변 (1개)

Sunny Choudhary
Sunny Choudhary 2023년 7월 11일
Hi
I debugged your code by printing i values.
What mistake I can see in your code is its printing sum of squares of 1 to 89 for multiple times
You are doing = (1^2 + 2^2+ ... + 89^2) some k times
But what we want is 1^2 + 2^2+ ... + 132^2) for single time
You can use this code to calculate the squares of all positive odd integers whose sum is greater than or equal to 3,000,000.
sum = 0;
n = 0;
i = 0;
while sum < 3000000
sum = sum + i * i;
n = n + 1;
i = i + 2;
end
n
n = 132
sum
sum = 3031864

카테고리

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

태그

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by