View Single Post
Old 2004-05-28, 16:26   #1
maheshexp
 
May 2004

2510 Posts
Lightbulb Fast way to square???

can any one help me to find out wheather it multiples faster to get the "square of a number i.e x^2 "or not. if you have better solution , could u please give me.

y(1) = 1;
y(n) = y(n-1) + ( 1 + 2* (n-1)), n > 1

eg: to find 4^2
y(1) = 1
y(2) = y(1) + (1 + 2*(1)) => 4
y(3) = y(2) + (1 + 2*(2)) => 9
y(4) = y(3) + (1 + 2*(3)) => 16

A CPP Program....

Code:
void test2() {
		long long max = 60000;
		long long y = 1;
		time_t t1, t2;
		
		time(&t1);
		for (long long  j = 0; j < max / 3; j++)
			for (long long  i = 1; i <= max; i++) {
				y = i * i;
			}
		time(&t2);
		cout<<"muls:\n\t"<<"t1:" << t1 << "\n\tt2:" <<t2 <<"\n"<<(t2-t1)<<endl;
		
		time(&t1);
		for (long long  j = 0; j < max / 3; j++)
			for (long long  i = 2; i <= max; i++) {
				y = y + (1 + (i << 1));
			}
		time(&t2);
		cout<<"muls:\n\t"<<"t1:" << t1 << "\n\tt2:" <<t2 <<"\n"<<(t2-t1)<<endl;
}
Output of CPP Program:

Code:
muls:
        t1:1080490498
        t2:1080490523
25 s
muls:
        t1:1080490523
        t2:1080490537
14 s
A java Program...
Code:
	private static void test1() {
		long max = 60000;
		long y = 1;
		long t1, t2;
		
		t1 = System.currentTimeMillis();
		for (int j = 0; j < max / 3; j++)
			for (int i = 1; i <= max; i++) {
				y = i * i;
			}
		t2 = System.currentTimeMillis();
		System.out.println("muls:" + (t2 - t1));
		
		t1 = System.currentTimeMillis();
		for (int j = 0; j < max / 3; j++)
			for (int i = 2; i <= max; i++) {
				y = y + (1 + (i << 1));
			}
		t2 = System.currentTimeMillis();
		System.out.println("mul:" + (t2 - t1));
	}
Output of Java Program....
Code:
muls:10031 ms
mul:5906 ms
maheshexp is offline   Reply With Quote