a059. 完全平方和
在a~b之間尋找平方數然後加總,所以要找平方後>=a與平方後<=b的兩個數當作起點和終點
開根號a之後可能是整數或小數,如果是小數就要「無條件進位」(ceiling),b則「無條件捨去」(floor)。
程式碼如下:
- /* Pa059.java
- * a059. 完全平方和
- *
- * 科皓不要
- * 2020/3/7
- */
- import java.util.Scanner;
- public class Pa059{
- public static void main(String[] args){
- Scanner scanner = new Scanner(System.in);
- while(scanner.hasNext()){
- int T = scanner.nextInt();
- for(int i = 1; i <= T; i++){
- int sum = 0;
- int a = (int)Math.ceil(Math.sqrt(scanner.nextInt()));
- int b = (int)Math.floor(Math.sqrt(scanner.nextInt()));
- for(; a <= b; a++){
- sum += a * a;
- }
- System.out.println("Case " + i + ": " + sum);
- }
- }
- }
- }
沒有留言:
張貼留言