Yêu cầu
– Nhập vào mảng 1 chiều số nguyên
– Viết hàm liệt kê các vị trí mà giá trị tại đó là số chính phương trong mảng 1 chiều số nguyên
Giải thuật
– Viết hàm kiểm tra số chính phương
– Viết hàm tìm vị trí số chính phương trong mảng
+ Đếm số lượng số chính phương trong mảng
+ Cấp phát mảng động lưu vị trí các phần tử chính phương
Code
package net.vncoding; import java.lang.Math; public class JavaCore { public static void main(String[] args) { int arr[] = {1, 3, -6, 13, 0, 20, 9, -7, 14, 0, 36, 28, 32, 11, 100}; int[] subArr = GetPosSquareElement(arr); if(subArr.length == 0) { System.out.println("Not found square number in array"); } else { System.out.format("Position of square number in array: \n"); for(int i = 0; i < subArr.length; i++) { System.out.print(subArr[i] + "\t"); } } } public static int[] GetPosSquareElement(int[] arr) { int cnt = 0; int i, j = 0; // Count the number of element belongs to [x; y] for(i = 0; i < arr.length; i++) { if(arr[i] > 0 && check_square_num(arr[i])) { cnt++; } } // Extract elements which belongs to [x;y] int[] subArr = new int[cnt]; for(i = 0; i < arr.length; i++) { if(arr[i] > 0 && check_square_num(arr[i])) { subArr[j++] = i; } } return subArr; } // Check whether number is a square or not? public static boolean check_square_num(int n) { int temp = (int)Math.sqrt(n); if(temp*temp == n) { return true; } else { return false; } } }
Kết quả
Leave a Reply
You must be logged in to post a comment.