序列的总和[硬核版]【难度:2级】:
答案1:
using System;
public static class Kata
{
public static long SequenceSum(long start, long end, long step)
{
if (Math.Sign(end-start) != Math.Sign(step))
return 0;
end -= (end-start)%step;
return (start+end)*(1+(end-start)/step)/2;
}
}
答案2:
public static class Kata
{
public static long SequenceSum(long s, long e, long d)
{
var n = (e-s) / d + 1;
return (e*d <= s*d) ? 0 : n*s + n*(n-1)*d/2;
}
}
答案3:
public static class Kata
{
public static long SequenceSum(long start, long end, long step)
{
if (step == 0 || step > 0 && end <= start || step < 0 && start <= end) return 0;
var count = (end - start) / step + 1;
return count * start + step *count* (count - 1) / 2;
}
}
答案4:
using System;
public static class Kata
{
public static long SequenceSum(long start, long end, long step)
{
if((end<start && step>0) || (end>start && step<0) || end==start)
return 0;
long count = ((end - start) / step) + 1;
return ((count - 1) * (step) + 2 * start) * count / 2;
}
}
答案5:
using System;
public static class Kata
{
public static long SequenceSum(long start, long end, long step)
{
if (start >= end && step > 0 || start <= end && step < 0) return 0;
long last = (end - start) % step == 0 ? end : end - (end - start) % step;
long n = (last - start) / step + 1;
long sum = (long)((start + last) / 2.0 * n);
return sum;
}
}
答案6:
using System;
public static class Kata {
public static long SequenceSum( long start, long end, long step ) {
if ( start >= end && step > 0 ) {
return 0;
}
if ( start <= end && step < 0 ) {
return 0;
}
long n = Math.Abs( ( end - start )/step ) + 1;
var a1 = start;
var an = a1 + step*( n - 1 );
var sum = ( ( a1 + an )/2.0 )*n;
return ( long ) sum;
}
}
答案7:
using System;
public static class Kata
{
public static long SequenceSum(long start, long end, long step)
{
long sum = 0;
if ((start > end && step > 0) || (end > start && step < 0) || start == end)
return 0;
long n = (end - start + step) / step;
long end1 = start + step * (n - 1);
sum = (start + end1) * n / 2;
return sum;
}
}
答案8:
using System;
using System.Linq;
public static class Kata
{
public static long SequenceSum(long start, long end, long step)
{
if (step > 0 && start>=end) return 0L;
if (step < 0 && start<=end) return 0L;
long a = (end-start)/step;
return (a+1)*start+step*a*(a+1)/2L;
}
}
答案9:
using System;
public static class Kata
{
public static long SequenceSum(long start, long end, long step)
{
if(end<start&&step>0 || end>start&&step<0 || end==start)
return 0;
long n=(end-start)/step+1;
return n*(2*start+(n-1)*step)/2;
}
}
答案10:
using static System.Math;
public static class Kata
{
public static long SequenceSum(decimal start, decimal end, decimal step)
{
if ((start >= end && step > 0) || (start <= end && step < 0))
return 0;
end = (end - start) - ((end - start) % step);
var count = Ceiling((end + Sign(step)) / step);
var prefix = Max(1, count) * start;
var suffix = end * (end + step) / (step * 2);
return (long)(prefix + suffix);
}
}