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