-2

I need to solve for the sum of (10^2 + 10^3) * 99, the sum will be total = (1100+1100+1100...(99 times)). I know most people don't like loops but I need to solve for this using a for loop. Here is what I have so far...

prob1 <- function(n){  
  total <- 1100
  for(i in 2:99) 
    total[i] <- sum(i^2 + i^3)  
  return(total)
}

This is what I get

[1]   1100     12     36     80    150    252    392    576    810   1100   1452   1872   2366   2940   3600
[16]   4352   5202   6156   7220   8400   9702  11132  12696  14400  16250  18252  20412  22736  25230  27900
[31]  30752  33792  37026  40460  44100  47952  52022  56316  60840  65600  70602  75852  81356  87120  93150
[46]  99452 106032 112896 120050 127500 135252 143312 151686 160380 169400 178752 188442 198476 208860 219600
[61] 230702 242172 254016 266240 278850 291852 305252 319056 333270 347900 362952 378432 394346 410700 427500
[76] 444752 462462 480636 499280 518400 538002 558092 578676 599760 621350 643452 666072 689216 712890 737100
[91] 761852 787152 813006 839420 866400 893952 922082 950796 980100

How can I get it to add correctly and return just the total as integer instead of an array? The total should be 108900 (I believe)

sertsedat
  • 3,490
  • 1
  • 25
  • 45
S.Galleg
  • 95
  • 1
  • 1
  • 8
  • **a.** You're getting what you code is asking for. What's the desired result? You're not using previous terms to get a cumulative sum, and the description just sounds like using the same numbers every time. **b.** Why the need for a `for` loop? `cumsum` and `Reduce` are nice functions. **c.** If you do use a `for` loop, preallocate a vector of the appropriate size or you'll get a nasty performance penalty. – alistaire Sep 25 '16 at 00:31
  • another way to write out is `x = (10^2 + 10^3) ` `Total = seq(x,x*99,x)` – JamesNEW Jan 14 '22 at 03:54

1 Answers1

5

I looked at your loop issue a little differently since you just wanted the total. Your code was adding elements to a vector with the total[i]. You instead want to just have i be an iterator for adding a number to another number. I initialized that to 0 with the first line.

total=0
for (i in 1:99) {
total<-total+(10^2 + 10^3)
}
total

[1] 108900

1100*99

[1] 108900

akaDrHouse
  • 2,190
  • 2
  • 20
  • 29
  • 1
    Thank you! That worked...it works without the last line of code 'i = i+1' for my understanding can you explain why I should include this? – S.Galleg Sep 25 '16 at 00:50
  • You are correct. It isn't needed. The loop does that. Sorry for the confusion. I will edit my post. – akaDrHouse Sep 25 '16 at 00:51
  • 1
    No worries, I just wanted to understand. Thank you for your time, I appreciate the help! – S.Galleg Sep 25 '16 at 00:53