Recaman 's sequence | Java program to print n - th number in Recaman 's sequence ; Prints first n terms of Recaman sequence ; Print first term and store it in a hash ; Print remaining terms using recursive formula . ; If arr [ i - 1 ] - i is negative or already exists . ; Driver code
import java . util . * ; class GFG { static void recaman ( int n ) { if ( n <= 0 ) return ; System . out . printf ( " % d , ▁ " , 0 ) ; HashSet < Integer > s = new HashSet < Integer > ( ) ; s . add ( 0 ) ; int prev = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int curr = prev - i ; if ( curr < 0 || s . contains ( curr ) ) curr = prev + i ; s . add ( curr ) ; System . out . printf ( " % d , ▁ " , curr ) ; prev = curr ; } } public static void main ( String [ ] args ) { int n = 17 ; recaman ( n ) ; } }