Results 1 to 3 of 3

Thread: displaying output from a sequence

  1. #1

    Thread Starter
    Addicted Member annie613's Avatar
    Join Date
    May 2003
    Location
    NY, NY
    Posts
    161

    displaying output from a sequence

    i used this code to generate a int N. I do this using (even)n=n/2 and (odd) n=3n+1 until n becomes 1. i use a System.out.println(n); to show the results, but what if i only wanted to show that last 4 numbers in the sequence... any suggestions.. thanks in advance annie

    Code:
    int n = 0;
    System.out.println("Please enter a number less than 100,000");
    KBI.pause();
    n = KBI.getint();
    while(n != 1)
    {
    System.out.print(n + " ");
    if(n % 2 == 0)
    n = n / 2;
    else
    n = 3 * n + 1;
    }
    System.out.println(n);

  2. #2
    Fanatic Member brown monkey's Avatar
    Join Date
    Jun 2004
    Location
    Cebu
    Posts
    552
    this mate?
    PHP Code:
    import java.io.*;
    import java.util.*;
    public class 
    document8{
       public static 
    void main(String[] args)throws IOException{
          
    BufferedReader stdin=new BufferedReader(
             new 
    InputStreamReader(System.in));
          
    System.out.println("Please enter a number less that 100,000 ");
          
    int n=Integer.parseInt(stdin.readLine());
          
    int[] n2=new int[n];
          
    int i=0;
          while(
    n!=1){
             
    System.out.print(n+" ");
             if(
    n%2==0n/=2;
             else 
    n=3*n+1;
             
    n2[i++]=n;
          }
          
    System.out.println(n);

          
    //display last 4
          
    int j=0;
          while(--
    i>=0&&j++<4System.out.println(n2[i]);
       }

    if not, i'm very very sorry.

  3. #3

    Thread Starter
    Addicted Member annie613's Avatar
    Join Date
    May 2003
    Location
    NY, NY
    Posts
    161
    cheers! annie
    this is what i ended up with....

    Code:
    //arrayList code    int n = 0;    
    System.out.println("Please enter a number less than 100,000");    KBI.pause();    
    n = KBI.getint();    
    ArrayList al = new ArrayList();    
    while(n != 1)    
    {      
    System.out.print(n + " ");      
    if(n % 2 == 0)        
    n = n / 2;      
    else        
    n = 3 * n + 1;        
    if (al.size < 4) 
    {        
    al.add(new Integer(n));      
    } else 
    {        
    al.remove(3);        
    al.add(new Integer(n));      
    }      
    }    
    for (int i=0;i<4;i++) 
    {      
    System.out.println(((Integer) al.get(i)).toString());    
    }
    Last edited by annie613; Jul 29th, 2004 at 12:09 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width