Recaman 's sequence | Prints first n terms of Recaman sequence ; Create an array to store terms ; First term of the sequence is always 0 ; Fill remaining terms using recursive formula . ; If arr [ i - 1 ] - i is negative or already exists . ; Driver code
function recaman ( n ) { let arr = new Array ( n ) ; arr [ 0 ] = 0 ; document . write ( arr [ 0 ] + " " ) ; for ( let i = 1 ; i < n ; i ++ ) { let curr = arr [ i - 1 ] - i ; let j ; for ( j = 0 ; j < i ; j ++ ) { if ( ( arr [ j ] == curr ) curr < 0 ) { curr = arr [ i - 1 ] + i ; break ; } } arr [ i ] = curr ; document . write ( arr [ i ] + " " ) ; } } let n = 17 ; recaman ( n ) ;