java - Get the next sequence in an arithmetic or geometric progression -
i want make application takes sequence of 3 numbers per line produce , stops when reaches sequence of zeros , prints if it's arithmetic progression or geometric progression , next number in series.
example input:
4 7 10 2 6 18 0 0 0
should output
ap 13 gp 54
here code wanna know what's wrong , possibilities won't work code.
import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstreamreader; public class main { static string s=""; public static void main (string[] args) throws ioexception { string c; string a[]; bufferedreader br = new bufferedreader(new inputstreamreader(system.in)); { c= br.readline(); = c.split(" "); if(c.charat(0)!='0'){ calc(a[1], a[2]); } }while((c.charat(0))!='0'); printer(s); } public static void calc(string a, string b){ int x = integer.parseint(a); int y = integer.parseint(b); if(y%x==0){ s += "gp" +" " + (y*(y/x)) + "z"; return; }else{ s += "ap" + " " + (y + (y-x)) + "z"; return; } } public static void printer(string s){ string p= ""; for(int =0;i<=s.length()-1;i++){ if(s.charat(i)!='z'){ p+= s.charat(i); }else{ system.out.println(p); p= ""; } } } }
your problem discover progression type incorrectly. example, 0 4 8
ap, algorithm gp. example: 8 4 2
gp, 2%4
return false
, saying ap. also, don't proceed cases when offered sequence not progression @ all.
it absolutely clear 3 numbers should involved. suppose integer numbers a, b, c
form ap or gp, , need discover progression is. simple math can used:
- if form ap,
a + c = b + b
. next elementc + c - b
- if form gp,
a * c = b * b
. next elementc * c / b
(please notice how +
changed *
, , -
/
, when switch ap gp).
Comments
Post a Comment