for loop - Integer square root in java -


i writing program integer square root of number. code:

import java.util.scanner; public class introot{     public static void main(string[] args){     int num;     system.out.print("enter non-negative integer: ");     scanner sc = new scanner(system.in);     num = sc.nextint();     int i;     int y=1;     (i=1; num>=i+(i+2); +=2){         ++y;     }     system.out.print(y);     } } 

the program should add odd positive integers 1 @ time (1+3+5+7+...) until next sum less or equal num, count number of odd numbers used give integer square root (and print number).

eg. integer square root of 12 3, since 1+3+5 = 9, , there 3 odd numbers in sum

currently program doesn't print correct number. "i" should start @ 1 , increase 2 each time. loop repeat until next sum of "i"'s greater "num", , "y" grow 1 each time give number of times "i" has grown. if input 7, "i" should stop when y=2, similarly, if input 4, should stop when y=2, , if input 49, should stop when y=7.

is there wrong code? or logic?

you've got few things wrong here's works

int currsum = 0; int oddcount = 0; for(int = 1; currsum + <= num; i+=2) {    currsum += i;    oddcount++; } 

basically check currsum = 1+3+5....+i < num , if current sum not greater num, adding next odd integer current sum, incrementing number of odd numbers seen, , checking again.


Comments