Expressing factorial n as sum of consecutive numbers | Javascript program to count number of ways we can express a factorial as sum of consecutive numbers ; sieve of Eratosthenes to compute the prime numbers ; Store all prime numbers ; function to calculate the largest power of a prime in a number ; Modular multiplication to avoid the overflow of multiplication Please see below for details https : www . geeksforgeeks . org / how - to - avoid - overflow - in - modular - multiplication / ; Returns count of ways to express n ! as sum of consecutives . ; We skip 2 ( First prime ) as we need to consider only odd primes ; compute the largest power of prime ; if the power of current prime number is zero in N ! , power of primes greater than current prime number will also be zero , so break out from the loop ; multiply the result at every step ; subtract 1 to exclude the case of 1 being an odd divisor ; Driver function
let MAX = 50002 ; let primes = [ ] ; function sieve ( ) { let isPrime = new Array ( MAX ) ; for ( let i = 0 ; i < MAX ; i ++ ) isPrime [ i ] = true ; for ( let p = 2 ; p * p < MAX ; p ++ ) { if ( isPrime [ p ] == true ) { for ( let i = p * 2 ; i < MAX ; i += p ) isPrime [ i ] = false ; } } for ( let p = 2 ; p < MAX ; p ++ ) if ( isPrime [ p ] == true ) primes . push ( p ) ; } function power ( x , y ) { let count = 0 ; let z = y ; while ( x >= z ) { count += Math . floor ( x / z ) ; z *= y ; } return count ; } function modMult ( a , b , mod ) { let res = 0 ; a = a % mod ; while ( b > 0 ) { if ( b % 2 == 1 ) res = ( res + a ) % mod ; a = ( a * 2 ) % mod ; b = Math . floor ( b / 2 ) ; } return res % mod ; } function countWays ( n , m ) { let ans = 1 ; for ( let i = 1 ; i < primes . length ; i ++ ) { let powers = power ( n , primes [ i ] ) ; if ( powers == 0 ) break ; ans = modMult ( ans , powers + 1 , m ) % m ; } if ( ( ( ans - 1 ) % m ) < 0 ) return ( ans - 1 + m ) % m ; else return ( ans - 1 ) % m ; } sieve ( ) ; let n = 4 , m = 7 ; document . write ( countWays ( n , m ) ) ;