Problem is available at http://www.spoj.com/problems/SAMER08F/
This problem is easy to solve if you understand the pattern.
If n = 1, there is one 1-by-1 square.
If n = 2, there is one 2-by-2 square and four 1-by-1 squares.
If n = 3, there is one 3-by-3 square, four 2-by-2 squares and nine 1-by-1 squares.
so if n=k , there is one k^2 + (k-1)^2 + (k-2)^2 + (k-3)^2 + ....... + 1^2 squares.
code is given below in java :
import java.util.Scanner;
import java.lang.*;
class spoj
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int val=0;
int sum=0;
int i=0;
while((val=s.nextInt())!=0){
for(i=1;i<=val;i++){
sum=sum+(int)(Math.pow(i,2));
}
System.out.println(sum);
sum=0;
}
}
}
This problem is easy to solve if you understand the pattern.
If n = 1, there is one 1-by-1 square.
If n = 2, there is one 2-by-2 square and four 1-by-1 squares.
If n = 3, there is one 3-by-3 square, four 2-by-2 squares and nine 1-by-1 squares.
so if n=k , there is one k^2 + (k-1)^2 + (k-2)^2 + (k-3)^2 + ....... + 1^2 squares.
code is given below in java :
import java.util.Scanner;
import java.lang.*;
class spoj
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int val=0;
int sum=0;
int i=0;
while((val=s.nextInt())!=0){
for(i=1;i<=val;i++){
sum=sum+(int)(Math.pow(i,2));
}
System.out.println(sum);
sum=0;
}
}
}
No comments:
Post a Comment