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

2 views (last 30 days)
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 Comments
Noah Sickels
Noah Sickels on 25 Sep 2020
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 on 25 Sep 2020
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?

Sign in to comment.

Answers (1)

Sunny Choudhary
Sunny Choudhary on 11 Jul 2023
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

Tags

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!