Print n Ulam sequence

PYTHON_CODE_FROM_OEIS
def isUlam(n, h, u, r):
  if h == 2: return False
  hu = u[0]; hr = r[0]
  if hr <= hu: return h == 1
  if hr + hu > n: r = r[1:]
  elif hr + hu < n: u = u[1:]
  else: h += 1; r = r[1:]; u = u[1:]
  return isUlam(n, h, u, r)
def UlamList(length):
  u = [1, 2]; r = [2, 1]; n = 2
  while len(u) < length:
    n += 1
    if isUlam(n, 0, u[:], r[:]):
      u.append(n); r.insert(0, n)
  return u

print(UlamList(59)) 
1 Like

import java.util.HashSet;
import java.util.Set;

//1,2,3,4,6,8,11,13,16,18,26,28,36,38,47,48…

public class PrintUlam{

public static void main(String args[]) {
 
	int n = 1;
	int m = 2;
	int count=0;
	int sum = n + m;
	int next = sum+1;
	int print = 0;
	
	Set<Integer> ulam = new HashSet<Integer>();
	ulam.add(n);
	ulam.add(m);
	ulam.add(sum);
	
	System.out.print(n +" "+ m +" "+sum+" ");
	
		for( int last = 1; last<= 100; last++) {
			
			for(int i=1; i<=sum/2;i++) {
			
				for(int j=sum/2; j<=sum; j++) {
	    			if(ulam.contains(i) && ulam.contains(j) && i!=j && (i + j) == next) {
	    				print = i+j;
	    				count++;
	    				}
				}
		}
		if( count < 2 && print != 0 ) {
			ulam.add(print);
			System.out.print(print +" ");	
		}
		next = next+1;
		sum = sum+1;
		count = 0;
		print = 0;
			}
}	

}

1 Like

hey can you please code it in python??

Why r u asking everyone to code, find the logic write the code yourself dude… code can be in a different platform/ environment but the logic will always remains same. Give it a try!!
For every next no. to be printed, divide it into halves, run the loop, if the individual no. in each of the two halves adds to make the next no., increment the counter, if the counter > 2 after the loop ends for that next no., skip the no. else store that (next) no. in a list. Don’t use the loop numbers. Use only the numbers present in that list that can be added to find the next no. Hope u got the logic. Happy coding.

thank you
yeah I will try