Write a program that will take in a positive integer n, and print out the nth term of the Recaman sequence. The program must use recursion to calculate its answer.
Here is a video explaining what the Recaman sequence is: https://www.youtube.com/watch?v=FGC5TdIiT9U
You don't have to watch it but it helps understand what it's about. The way to calculate the nth term (represented by a(n)) is:
This says that the 0th term is 0, and all other terms are the previous term plus or minus the term number. You subtract the term number if it will result in a positive number, and if the resulting number has not already been used in the sequence. Otherwise, add the term number instead. Copy+paste your program in the comments below. If you have any questions, feel free to email me.
Here are some terms of the sequence, starting with the 0th term.
0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9, 24, 8, 25, 43, 62, 42, 63, 41, 18, 42, 17, 43, 16, 44, 15, 45, 14, 46, 79, 113, 78, 114, 77, 39, 78, 38, 79, 37, 80, 36, 81, 35, 82, 34, 83, 33, 84, 32, 85, 31, 86, 30, 87, 29, 88, 28, 89, 27, 90, 26, 91, 157, 224, 156, 225, 155
import java.util.*;
import java.io.*;
class Homework {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number for n");
int n = in.nextInt();
recaman(n);
}
public static void recaman(int n){
int arr[] = new int[n];
arr[0] = 0;
System.out.print(arr[0]+" ,");
for(int i = 1; i < n; i++){
int curr = arr[i - 1] - i;
int j;
for(j = 1; j < i; j++){
if((arr[j] == curr) || curr < 0){
curr = arr[i - 1] + i;
break;
}
}
arr[i] = curr;
System.out.print(arr[i]+", ");
}
}
}
i bet my code is wrong but sure import java.util.*; import java.io.*; class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Scanner is now ready"); int n = in.nextInt(); ArrayList<Integer> A = new ArrayList<Integer>(n+1); int i = 1; int m = 0; A.add(0); if(n == 0){ } while(i < n){ if((A.get(i-1)-i) > 0){ if(A.contains(A.get(i-1)-i) == false){ A.add((i-1)-i); } } else{ A.add((i-1)+i); } i++; } System.out.println("Recaman sequence number " + n + ":" + A.get(n)); } }
def recaman(n, seen): n = int(n) if n == 0: seen.append(0) return 0 else: a = recaman(n - 1, seen) minus = a - n plus = a + n if minus > 0 and minus not in seen: seen.append(minus) return minus else: seen.append(plus) return plus used = [ ] num = recaman(input('Number: '), used) print(num)