Squares of all positive odd integers whose sum is greater than or equal to 3,000,000
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Steven Lord
el 25 de Sept. de 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?
Respuestas (1)
Sunny Choudhary
el 11 de Jul. de 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
sum
0 comentarios
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!