Open In App

Recaman’s sequence

Last Updated : 27 Aug, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an integer n. Print first n elements of Recaman’s sequence.
Examples: 
 

Input : n = 6
Output : 0, 1, 3, 6, 2, 7

Input  : n = 17
Output : 0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 
         11, 22, 10, 23, 9, 24, 8

It is basically a function with domain and co-domain as natural numbers and 0. It is recursively defined as below: 
Specifically, let a(n) denote the (n+1)-th term. (0 is already there). 
The rule says: 

a(0) = 0,
if n > 0 and the number is not 
   already included in the sequence,
     a(n) = a(n - 1) - n 
else 
     a(n) = a(n-1) + n. 

 

Recommended Problem

Below is a simple implementation where we store all n Recaman Sequence numbers in an array. We compute the next number using the recursive formula mentioned above. 
 

C++




// C++ program to print n-th number in Recaman's
// sequence
#include <bits/stdc++.h>
using namespace std;
 
// Prints first n terms of Recaman sequence
int recaman(int n)
{
    // Create an array to store terms
    int arr[n];
 
    // First term of the sequence is always 0
    arr[0] = 0;
    printf("%d, ", arr[0]);
 
    // Fill remaining terms using recursive
    // formula.
    for (int i=1; i< n; i++)
    {
        int curr = arr[i-1] - i;
        int j;
        for (j = 0; j < i; j++)
        {
            // If arr[i-1] - i is negative or
            // already exists.
            if ((arr[j] == curr) || curr < 0)
            {
                curr = arr[i-1] + i;
                break;
            }
        }
 
        arr[i] = curr;
        printf("%d, ", arr[i]);
    }
}
 
// Driver code
int main()
{
    int n = 17;
    recaman(n);
    return 0;
}


Java




// Java program to print n-th number in Recaman's
// sequence
import java.io.*;
 
class GFG {
     
    // Prints first n terms of Recaman sequence
    static void recaman(int n)
    {
        // Create an array to store terms
        int arr[] = new int[n];
     
        // First term of the sequence is always 0
        arr[0] = 0;
        System.out.print(arr[0]+" ,");
     
        // Fill remaining terms using recursive
        // formula.
        for (int i = 1; i < n; i++)
        {
            int curr = arr[i - 1] - i;
            int j;
            for (j = 0; j < i; j++)
            {
                // If arr[i-1] - i is negative or
                // already exists.
                if ((arr[j] == curr) || curr < 0)
                {
                    curr = arr[i - 1] + i;
                    break;
                }
            }
     
            arr[i] = curr;
            System.out.print(arr[i]+", ");
             
        }
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int n = 17;
        recaman(n);
 
    }
}
 
// This code is contributed by vt_m


Python 3




# Python 3 program to print n-th
# number in Recaman's sequence
 
# Prints first n terms of Recaman
# sequence
def recaman(n):
 
    # Create an array to store terms
    arr = [0] * n
 
    # First term of the sequence
    # is always 0
    arr[0] = 0
    print(arr[0], end=", ")
 
    # Fill remaining terms using
    # recursive formula.
    for i in range(1, n):
     
        curr = arr[i-1] - i
        for j in range(0, i):
         
            # If arr[i-1] - i is
            # negative or already
            # exists.
            if ((arr[j] == curr) or curr < 0):
                curr = arr[i-1] + i
                break
             
        arr[i] = curr
        print(arr[i], end=", ")
 
# Driver code
n = 17
 
recaman(n)
 
# This code is contributed by Smitha.


C#




// C# program to print n-th number in Recaman's
// sequence
using System;
 
class GFG {
     
    // Prints first n terms of Recaman sequence
    static void recaman(int n)
    {
        // Create an array to store terms
        int []arr = new int[n];
     
        // First term of the sequence is always 0
        arr[0] = 0;
        Console.Write(arr[0]+" ,");
     
        // Fill remaining terms using recursive
        // formula.
        for (int i = 1; i < n; i++)
        {
            int curr = arr[i - 1] - i;
            int j;
            for (j = 0; j < i; j++)
            {
                // If arr[i-1] - i is negative or
                // already exists.
                if ((arr[j] == curr) || curr < 0)
                {
                    curr = arr[i - 1] + i;
                    break;
                }
            }
     
            arr[i] = curr;
        Console.Write(arr[i]+", ");
             
        }
    }
     
    // Driver code
    public static void Main ()
    {
        int n = 17;
        recaman(n);
 
    }
}
 
// This code is contributed by vt_m.


PHP




<?php
// PHP program to print n-th
// number in Recaman's sequence
 
// Prints first n terms
// of Recaman sequence
function recaman($n)
{
     
    // First term of the
    // sequence is always 0
    $arr[0] = 0;
    echo $arr[0], ", ";
 
    // Fill remaining terms
    // using recursive formula.
    for ($i = 1; $i < $n; $i++)
    {
            $curr = $arr[$i - 1] - $i;
            $j;
        for ($j = 0; $j < $i; $j++)
        {
             
            // If arr[i-1] - i
            // is negative or
            // already exists.
            if (($arr[$j] == $curr) || $curr < 0)
            {
                $curr = $arr[$i-1] + $i;
                break;
            }
        }
 
        $arr[$i] = $curr;
        echo $arr[$i], ", ";
    }
}
 
    // Driver Code
    $n = 17;
    recaman($n);
     
// This code is contributed by Ajit
?>


Javascript




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


Output:  

0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9, 24, 8, 

Time Complexity : O(n2
Auxiliary Space : O(n), since n extra space has been added
Optimizations : 
We can use hashing to store previously computed values and can make this program work in O(n) time. 
 

C++




// C++ program to print n-th number in Recaman's
// sequence
#include <bits/stdc++.h>
using namespace std;
 
// Prints first n terms of Recaman sequence
void recaman(int n)
{
    if (n <= 0)
      return;
 
    // Print first term and store it in a hash
    printf("%d, ", 0);
    unordered_set<int> s;
    s.insert(0);
 
    // Print remaining terms using recursive
    // formula.
    int prev = 0;
    for (int i=1; i< n; i++)
    {
        int curr = prev - i;
 
        // If arr[i-1] - i is negative or
        // already exists.
        if (curr < 0 || s.find(curr) != s.end())
           curr = prev + i;
 
        s.insert(curr);
 
        printf("%d, ", curr);
        prev = curr;
    }
}
 
// Driver code
int main()
{
    int n = 17;
    recaman(n);
    return 0;
}


Java




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


Python3




# Python3 program to print n-th number in
# Recaman's sequence
 
# Prints first n terms of Recaman sequence
def recaman(n):
 
    if(n <= 0):
        return
 
    # Print first term and store it in a hash
    print(0, ",", end='')
    s = set([])
    s.add(0)
 
    # Print remaining terms using recursive
    # formula.
    prev = 0
    for i in range(1, n):
 
        curr = prev - i
 
        # If arr[i-1] - i is negative or
        # already exists.
        if(curr < 0 or curr in s):
            curr = prev + i
 
        s.add(curr)
 
        print(curr, ",", end='')
        prev = curr
 
# Driver code
if __name__=='__main__':
    n = 17
    recaman(n)
 
# This code is contributed by
# Sanjit_Prasad


C#




// C# program to print n-th number
// in Recaman's sequence
using System;
using System.Collections.Generic;
 
class GFG
{
 
// Prints first n terms of Recaman sequence
static void recaman(int n)
{
    if (n <= 0)
    return;
 
    // Print first term and store it in a hash
    Console.Write("{0}, ", 0);
    HashSet<int> s = new HashSet<int>();
    s.Add(0);
 
    // Print remaining terms using
    // recursive formula.
    int prev = 0;
    for (int i = 1; i < n; i++)
    {
        int curr = prev - i;
 
        // If arr[i-1] - i is negative or
        // already exists.
        if (curr < 0 || s.Contains(curr))
            curr = prev + i;
 
        s.Add(curr);
 
        Console.Write("{0}, ", curr);
        prev = curr;
    }
}
 
// Driver code
public static void Main(String[] args)
{
    int n = 17;
    recaman(n);
}
}
 
// This code is contributed by Princi Singh


PHP




<?php
// PHP program to print n-th number in
// Recaman's sequence
 
// Prints first n terms of Recaman sequence
function recaman($n)
{
    if($n <= 0)
        return;
 
    // Print first term and store
    // it in a hash
    print("0, ");
    $s = array();
    array_push($s, 0);
 
    // Print remaining terms using recursive
    // formula.
    $prev = 0;
    for ($i = 1; $i < $n; $i++)
    {
        $curr = $prev - $i;
 
        // If arr[i-1] - i is negative or
        // already exists.
        if($curr < 0 or in_array($curr, $s))
            $curr = $prev + $i;
 
        array_push($s, $curr);
 
        print($curr.", ");
        $prev = $curr;
    }
         
}
 
// Driver code
$n = 17;
recaman($n);
 
// This code is contributed by chandan_jnu
?>


Javascript




<script>
 
//  Javascript program to print n-th number
// in Recaman's sequence
 
// Prints first n terms of Recaman sequence
function recaman(n)
{
    if (n <= 0)
    return;
  
    // Print first term and store it in a hash
    document.write(0 + ", ");
    let s = new Set();
    s.add(0);
  
    // Print remaining terms using
    // recursive formula.
    let prev = 0;
    for (let i = 1; i< n; i++)
    {
        let curr = prev - i;
  
        // If arr[i-1] - i is negative or
        // already exists.
        if (curr < 0 || s.has(curr))
            curr = prev + i;
  
        s.add(curr);
  
        document.write(curr + ", ");
        prev = curr;
    }
}
     
    // Driver code
     
    let n = 17;
    recaman(n);
     
</script>


Output: 
 

0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9, 24, 8, 

Time Complexity : O(n) 
Auxiliary Space : O(n), since n extra space has been taken.

 



Previous Article
Next Article

Similar Reads

Find original sequence from Array containing the sequence merged many times in order
Given a number N and an array arr[] that consist of merging N length sequence of distinct integers any number of times maintaining the relative order of elements in the initial sequence. The task is to find the initial sequence of length N maintaining the right order. Examples: Input: N = 4, arr[] = {1, 13, 1, 24, 13, 24, 2, 2}Output: 1 13 24 2 Exp
10 min read
Finding nth term of any Polynomial Sequence
Given a few terms of a sequence, we are often asked to find the expression for the nth term of this sequence. While there is a multitude of ways to do this, In this article, we discuss an algorithmic approach which will give the correct answer for any polynomial expression. Note that this method fails for trigonometric, exponential or other transce
4 min read
Convert String into Binary Sequence
Given a string of character the task is to convert each character of a string into the equivalent binary number. Examples : Input : GFG Output : 1000111 1000110 1000111 Input : geeks Output : 1100111 1100101 1100101 1101011 1110011 The idea is to first calculate the length of the string as n and then run a loop n times. In each iteration store ASCI
5 min read
Length of Longest increasing sequence of nodes in a given Graph
Given a graph root, the task is to find the length of the longest increasing sequence in the graph. Example: Input: root = 7----17 / \ 1----2----5 4 / \ \ 11 6----8 / 12Output: 6 Explanation: The longest increasing sequence in the graph consists of the nodes 1, 2, 5, 6, 8, 12 Input: 2 / \ 3 1 / \ 5 6Output: 4 Approach: The given problem can be solv
13 min read
Sum of numbers from 1 to N which are in Fibonacci Sequence
Given an integer N, the task is to find the sum of numbers from 1 to N which are in Fibonacci sequence. First few Fibonacci numbers are 1, 1, 2, 3, 5, 8, 13, 21, 34, ....Examples: Input: N = 5 Output: 12 1 + 1 + 2 + 3 + 5 = 12Input: N = 10 Output: 20 1 + 1 + 2 + 3 + 5 + 8 = 20 Approach: Loop through all the Fibonacci numbers which are less than N.I
4 min read
Number of sub-sequence such that it has one consecutive element with difference less than or equal to 1
Given an array arr[] of N elements. The task is to find the number of sub-sequences which have at least two consecutive elements such that absolute difference between them is ? 1. Examples: Input: arr[] = {1, 6, 2, 1} Output: 6 {1, 2}, {1, 2, 1}, {2, 1}, {6, 2, 1}, {1, 1} and {1, 6, 2, 1} are the sub-sequences that have at least one consecutive pai
7 min read
Minimum steps required to rearrange given array to a power sequence of 2
Given an array arr[] consisting of N positive integers, the task is to find the minimum steps required to make the given array of integers into a sequence of powers of 2 by the following operations: Reorder the given array. It doesn't count as a step.For each step, select any index i from the array and change arr[i] to arr[i] ? 1 or arr[i] + 1. A s
4 min read
Count inversions in a sequence generated by appending given array K times
Given an array arr[], the task is to append the given array exactly K - 1 times to its end and print the total number of inversions in the resulting array. Examples: Input: arr[]= {2, 1, 3}, K = 3Output: 12Explanation:Appending 2 copies of array arr[] modifies arr[] to {2, 1, 3, 2, 1, 3, 2, 1, 3}The pairs (arr[i], arr[j]), where i < j and arr[i]
7 min read
Find N distinct integers with GCD of sequence as 1 and GCD of each pair greater than 1
Given an integer N, the task is to find a sequence of N distinct positive integers such that the Greatest Common Divisor of the sequence is 1 and GCD of all possible pairs of elements is greater than 1. Input: N = 4Output: 84 60 105 70Explanation: The GCD(84, 60, 105, 70) is 1 and the GCD of all possible pair of elements i.e, {(84, 60), (84, 105),
5 min read
Generic Class in Java
Java Generics was introduced to deal with type-safe objects. It makes the code stable.Java Generics methods and classes, enables programmer with a single method declaration, a set of related methods, a set of related types. Generics also provide compile-time type safety which allows programmers to catch invalid types at compile time. Generic means
4 min read
Introduction to Electronic Mail
Introduction:Electronic mail, commonly known as email, is a method of exchanging messages over the internet. Here are the basics of email:An email address: This is a unique identifier for each user, typically in the format of name@domain.com.An email client: This is a software program used to send, receive and manage emails, such as Gmail, Outlook,
4 min read
Java IO : Input-output in Java with Examples
Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These streams support all the types of objects, data-types, characters, files etc to fully execute the I/O operations. Before exploring various input and output streams lets look at 3 standard or default streams that Java has to provide
7 min read
Java Arithmetic Operators with Examples
Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types: Arithmetic Operator
6 min read
For Loop in Java
Loops in Java come into use when we need to repeatedly execute a block of statements. Java for loop provides a concise way of writing the loop structure. The for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping. Let us understand Java for loop with
7 min read
Building Heap from Array
Given an array of N elements. The task is to build a Binary Heap from the given array. The heap can be either Max Heap or Min Heap. Examples: Input: arr[] = {4, 10, 3, 5, 1}Output: Corresponding Max-Heap: 10 / \ 5 3 / \4 1 Input: arr[] = {1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17}Output: Corresponding Max-Heap: 17 / \ 15 13 / \ / \ 9 6 5 10 / \ / \ 4 8 3
14 min read
Insertion and Deletion in Heaps
Deletion in Heap:Given a Binary Heap and an element present in the given Heap. The task is to delete an element from this Heap. The standard deletion operation on Heap is to delete the element present at the root node of the Heap. That is if it is a Max Heap, the standard deletion operation will delete the maximum element and if it is a Min heap, i
15+ min read
Association Rule
Association rule mining finds interesting associations and relationships among large sets of data items. This rule shows how frequently a itemset occurs in a transaction. A typical example is a Market Based Analysis. Market Based Analysis is one of the key techniques used by large relations to show associations between items.It allows retailers to
3 min read
Data encryption standard (DES) | Set 1
This article talks about the Data Encryption Standard (DES), a historic encryption algorithm known for its 56-bit key length. We explore its operation, key transformation, and encryption process, shedding light on its role in data security and its vulnerabilities in today's context. What is DES?Data Encryption Standard (DES) is a block cipher with
15+ min read
Priority Queue in Python
Priority Queues are abstract data structures where each data/value in the queue has a certain priority. For example, In airlines, baggage with the title “Business” or “First-class” arrives earlier than the rest. Priority Queue is an extension of the queue with the following properties. An element with high priority is dequeued before an element wit
2 min read
Introduction to Internet of Things (IoT) - Set 1
IoT stands for Internet of Things. It refers to the interconnectedness of physical devices, such as appliances and vehicles, that are embedded with software, sensors, and connectivity which enables these objects to connect and exchange data. This technology allows for the collection and sharing of data from a vast network of devices, creating oppor
9 min read
Services and Segment structure in TCP
The Transmission Control Protocol is the most common transport layer protocol. It works together with IP and provides a reliable transport service between processes using the network layer service provided by the IP protocol. The various services provided by the TCP to the application layer are as follows: Process-to-Process Communication - TCP pro
5 min read
Block Cipher modes of Operation
Encryption algorithms are divided into two categories based on the input type, as a block cipher and stream cipher. Block cipher is an encryption algorithm that takes a fixed size of input say b bits and produces a ciphertext of b bits again. If the input is larger than b bits it can be divided further. For different applications and uses, there ar
5 min read
Carrier Sense Multiple Access (CSMA)
Carrier Sense Multiple Access (CSMA) is a method used in computer networks to manage how devices share a communication channel to transfer the data between two devices. In this protocol, each device first sense the channel before sending the data. If the channel is busy, the device waits until it is free. This helps reduce collisions, where two dev
9 min read
Converting Context Free Grammar to Chomsky Normal Form
Prerequisite - Simplifying Context Free Grammars A context free grammar (CFG) is in Chomsky Normal Form (CNF) if all production rules satisfy one of the following conditions: A non-terminal generating a terminal (e.g.; X->x) A non-terminal generating two non-terminals (e.g.; X->YZ) Start symbol generating ε. (e.g.; S-> ε) Consider the following gra
4 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Carry Look-Ahead Adder
The adder produce carry propagation delay while performing other arithmetic operations like multiplication and divisions as it uses several additions or subtraction steps. This is a major problem for the adder and hence improving the speed of addition will improve the speed of all other arithmetic operations. Hence reducing the carry propagation de
5 min read
std::gcd | C++ inbuilt function for finding GCD
In many competitive programming problems, we need to find greatest common divisor also known as gcd. Euclids algorithm to find gcd has been discussed here.C++ has the built-in function for calculating GCD. This function is present in header file. Syntax for C++14 : Library: 'algorithm' __gcd(m, n) Parameter : m, n Return Value : 0 if both m and n a
2 min read
Difference Between Structure and Union in C
Structures in C is a user-defined data type available in C that allows to combining of data items of different kinds. Structures are used to represent a record. Defining a structure: To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than or equal to one member. The format of the struct
4 min read
File Allocation Methods
The allocation methods define how the files are stored in the disk blocks. There are three main disk space or file allocation methods. Contiguous Allocation Linked Allocation Indexed Allocation The main idea behind these methods is to provide: Efficient disk space utilization. Fast access to the file blocks. All the three methods have their own adv
5 min read
SQL Functions (Aggregate and Scalar Functions)
SQL Functions are built-in programs that are used to perform different operations on the database. There are two types of functions in SQL: Aggregate FunctionsScalar FunctionsSQL Aggregate FunctionsSQL Aggregate Functions operate on a data group and return a singular output. They are mostly used with the GROUP BY clause to summarize data.  Some com
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg