Sunday, 5 October 2008

SquareNumbers.java : Solution for Al-Khawarizmi 08,Question A (UPDATED)

Sorry for late submission of this article which I promised long ago to publish it.

Questions of Al-Khawarizmi 08 can be viewed here:

http://www.scribd.com/doc/6403834/alkhawarizmi08

Questions of Al-Khawarizmi 08 can be downloaded here:

http://www.usaupload.net/d/1f40e9jjzl7

/**

* @author KaibaTheLegacy

* My modified ICPC Al-Khawarizmi 08 Question A

* solution in Java. Refer to Original question for

* more details.

*

* My team (USIM Spyjak) solved only this question

* during the competition. ;-)

*/

import java.util.*;

public class SquareNumbers {


/**

* @param args

*/

public static void main(String[] args)

{

// TODO Auto-generated method stub

int a,b,sum=0,c[] = new int [10000]; //Create an array contain of 10000 elements.


for ( int i=0; i<c.length;i++)

{

c[i] = i*i; //Create array of square numbers from 1^2 to 10000^2

}

/*

Another interesting use of Scanner to read from file

java SquareNumbers <>

create text.txt with this format:

1 20

1 50

1 36

0 0

*/

Scanner s = new Scanner (System.in);

while (s.hasNext()==true)

{

sum=0;

a=s.nextInt();

b=s.nextInt();

if (a==0 && b==0) {System.exit(0);} //if a and b are 0, the program will terminate

for (int i =a;i<=b;i++)

{

/*Using binary search to find whether i is a square number or not.

if true Arrays.binarySearch(c,i) >=0

if false, Arrays.binarySearch (c,i) < 0

*/

if (Arrays.binarySearch(c, i) >=0)


{

sum++;


}


}

System.out.println(sum);}

}


}


No comments:

Google custom search

Custom Search