Write a program that calculates sum of the integers numbers

3 vues (au cours des 30 derniers jours)
Aaron Moris
Aaron Moris le 11 Avr 2011
Commenté : DGM le 4 Mar 2023
What is the product if the question is write a program that calculates and prints the sum of the even integers from 2 to 30?

Réponses (5)

Florin Neacsu
Florin Neacsu le 11 Avr 2011
2+4+6+...+30=2(1+2+3+...+15)=2*(15*16)/2=15*16
So 2+4+...+n = floor(n/2)*(floor(n/2)+1).
Regards, Florin

Matt Fig
Matt Fig le 11 Avr 2011
The product would be the sum of the even integers from 2 to 30 ;-).
Seriously, what have you tried so far on this homework problem?
  2 commentaires
Sean de Wolski
Sean de Wolski le 11 Avr 2011
You might need some bubble wrap for that.
Paulo Silva
Paulo Silva le 11 Avr 2011
I hate when it takes more time to understand what people want than to make their answer!

Connectez-vous pour commenter.


Paulo Silva
Paulo Silva le 11 Avr 2011
v=2:30;
sum(v(~mod(v,2)))
  3 commentaires
Image Analyst
Image Analyst le 15 Août 2017
mod(v, 2) will be either 0 or 1. The tilde inverts that, so 0 becomes 1, and 1 becomes 0.
DGM
DGM le 4 Mar 2023
Importantly, using ~ implicitly casts the numeric result from mod() to logical (along with doing the inversion). Otherwise, the indexing operation would fail if the indices were numeric 0 and 1, as you'd be trying to access the zeroth element of v.

Connectez-vous pour commenter.


Doug Eastman
Doug Eastman le 11 Avr 2011
  2 commentaires
Paulo Silva
Paulo Silva le 11 Avr 2011
that's simple but if you change the start value from 2 to 1 you do the sum of odd numbers instead, also if the last value is 31 or some odd number the result won't be correct, unfortunately that's not very flexible code.
Paulo Silva
Paulo Silva le 11 Avr 2011
btw that does work and is a good answer for the question (only if the values don't change), +1 vote

Connectez-vous pour commenter.


Matt Tearle
Matt Tearle le 11 Avr 2011
disp(240)
Or, for pedants who claim that evaluation is not the same as calculation,
disp(239+1)
  1 commentaire
Sean de Wolski
Sean de Wolski le 11 Avr 2011
This is definitely the most compact and efficient way to do this. +1.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by