Filter löschen
Filter löschen

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

7 Ansichten (letzte 30 Tage)
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 Kommentare
Noah Sickels
Noah Sickels am 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 am 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?

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Sunny Choudhary
Sunny Choudhary am 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

Kategorien

Mehr zu Startup and Shutdown finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by