|
-
Jul 27th, 2004, 01:10 PM
#1
Thread Starter
Addicted Member
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);
-
Jul 28th, 2004, 02:50 AM
#2
Fanatic Member
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==0) n/=2;
else n=3*n+1;
n2[i++]=n;
}
System.out.println(n);
//display last 4
int j=0;
while(--i>=0&&j++<4) System.out.println(n2[i]);
}
}
if not, i'm very very sorry.
-
Jul 29th, 2004, 07:41 AM
#3
Thread Starter
Addicted Member
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|