[Jprogramming] Another Quora Problem
Don Kelly
dhky at shaw.ca
Tue Sep 5 01:58:16 UTC 2017
correction sum=: ]1+] for even numbers only from 2 to n%2
For numbers from 1 to n the sum is (n+1)*n%2 .
In the case that you give x= sum of a+ (n-1)b, which should be
a+sum(n-1*b) which can be simplified to a +b(1+2+3+..n-1)which becomes
a +b*n*(n-1)%2 As you are considering a +(a+b)+ (a+2b) etc then this
becomes (a*n) +b*n*(n-1)%2 which can be reduced to
a +1r2*b*]*1+]
Try it
Don
On 2017-08-31 7:39 PM, Don Kelly wrote:
> The pairing eliminates the brute force summing of the series. This is
> what Gauss found. In the case of only even numbers from 2 to n , this
> works. In the case of 42 there are 21 even numbers of which 20 can be
> paired off pairs 2+42,4+40 etc, each averaging 22 and there is an
> unpaired number which is also 22 so we have 21*22. we could use
>
> sum=: ]1+]
>
> sum 21
>
> 462 But 'evensum ' below avoids the onerous task of dividing 42 by
> 2 before entry
>
>
> evensum=: 1r4*]*2+]
>
> evensum 42
> 462
>
> evensum 10 100 1000 10000
>
> 30 2550 250500 25005000
>
>
> If you want numbers >4 to 42 then -/evensum 42 4 does the trick
>
>
>
> On 2017-08-30 9:27 PM, Xiao-Yong Jin wrote:
>>> On Aug 30, 2017, at 10:43 PM, Don Kelly <dhky at shaw.ca> wrote:
>>>
>>> I agree with your opinion of what Skip wrote. looking back to Gauss
>>> and figuring out the symmetry works for both odd and even cases (42
>>> &43 for example. However in his statement the numbers are 1...21
>>> where the numbers are 2 to 42 all even numbers- the result is still
>>> 21*22 . 42%2 is 21 which is odd so that there is 1 number that isn't
>>> paired and 20 pairs averaging 22 and the oddball is 1 number =22
>>> Hence 22*21. The same result is for 1 to 43 as the odd numbers are
>>> ignored. If one considers evens between 2 and 44, there are 22 pairs
>>> (no oddball) averaging 23- the same rule works average =1+number of
>>> pairs. For summing odd numbers, add 1 to each number, drop the odds
>>> and do the even sum- then subtract the total (21 in this case to get
>>> 462-21=441.
>> I don't understand why you worry about pairing, but if j code makes
>> it easier to understand, here is a derivation I learned from my
>> elementary school.
>>
>> NB. for any evenly spaced sequence X: a, a+b, a+2*b, ... , a+(n-1)*b
>> X =. a+n*i.b
>> ( +/ -: +/@|. ) X
>> ( +/ -: -:@(+/ + +/@|.) ) X
>> ( +/ -: -:@([:+/ +/@(,:|.)) ) X
>> ( +/ -: -:@([:+/ ##{.+{:) ) X
>> ( +/ -: -:@(#*{.+{:) ) X
>>
>> ----------------------------------------------------------------------
>> For information about J forums see http://www.jsoftware.com/forums.htm
>
> ----------------------------------------------------------------------
> For information about J forums see http://www.jsoftware.com/forums.htm
More information about the Programming
mailing list