text: Count ways to express a number as sum of consecutive numbers | A Java program to count number of ways to express N as sum of consecutive numbers . ; Utility method to compute number of ways in which N can be represented as sum of consecutive number ; constraint on values of L gives us the time Complexity as O ( N ^ 0.5 ) ; Driver code to test above function
code: public class SumConsecutiveNumber { static int countConsecutive ( int N ) { int count = 0 ; for ( int L = 1 ; L * ( L + 1 ) < 2 * N ; L ++ ) { double a = ( double ) ( ( 1.0 * N - ( L * ( L + 1 ) ) / 2 ) / ( L + 1 ) ) ; if ( a - ( int ) a == 0.0 ) count ++ ; } return count ; } public static void main ( String [ ] args ) { int N = 15 ; System . out . println ( countConsecutive ( N ) ) ; N = 10 ; System . out . println ( countConsecutive ( N ) ) ; } }