Rishav
Rishav

Reputation: 103

Count ways to express a number as sum of consecutive numbers

Count ways to express a number as sum of consecutive numbers. Say 21 , there are 3 ways to get it [1,2,3,4,5,6] , [6,7,8] and [10,11] .

While I was looking for some solutions on internet I came to code snippet which I am unable to understand . Or mathematical theory behind it . Though it gives a correct answer .

long countConsecutive(long num){
  long sumOfFirstIntegers = 3;        
  long count = 0;       

  for(long i = 2 ; sumOfFirstIntegers<=num; ++i){                         
    if((i%2==0)?(num%i==i/2): (num%i==0)){                      
      ++count;               
    }             
    sumOfFirstIntegers+=i+1;                    
  }           
  return count;          
}

Upvotes: 1

Views: 954

Answers (2)

Ankit Arora
Ankit Arora

Reputation: 1

This Program is written in Python very simple formula I applied

Sum of Arithmetic Sequence Formula When the Last Term is Given S = n⁄2 (a + L)

N=15
result=0
for start in range(1,N):
    cnt=1
    for end in range(start,N):
        sum1= cnt/2*(start+end)
        cnt=cnt+1
        if(sum1==N):
            result=result+1
            #print(start,end)
print(result)   

Upvotes: 0

GhostCat
GhostCat

Reputation: 140427

Independent of the maths, this here is probably the line causing you a headache:

if((i%2==0)?(num%i==i/2): (num%i==0)) { 

one can rewrite that like:

bool condition;
if (i%2 == 0) {
  condition = num%i == i/2;
} else {
  condition = num%&i == 0;
}
if (condition) { ++count; }

So the ternary operator is used to select a boolean condition, and % is the modulo operator.

For the math behind all of that, I delegate to geeksforce.

Upvotes: 1

Related Questions