Yêu cầu:
– Cho mảng số nguyên
– Tìm số chính phương đầu tiên trong mảng số nguyên. Nếu không tìm thấy, trả về -1
Giải thuật:
– Duyệt mảng, kiểm tra từng phần tử xem có phải số chính phương không.
Code
/************************************************************ * Author: VNCODING * History * 2016/12/24 first create VNCODING *************************************************************/ #include <stdio.h> #include <conio.h> #define MAX_SIZE_ARR 100 bool is_squarenumber(int); int get_first_squarenumber(int*, int); int main() { int arr[MAX_SIZE_ARR]; int n, i; int res; do { printf("n = "); scanf("%d", &n); }while(n <= 0 || n > 100); // Input array for(i = 0; i < n; i++) { printf("\narr[%d] = ", i); scanf("%d", &arr[i]); } res = get_first_squarenumber(arr, n); if (res == -1) { printf("\nNot found!!!"); } else { printf("\nThe first square number is: %d", res); } getch(); return 0; } bool is_squarenumber(int n) { int i; bool res = false; for (i = 0; i <= n; i++) { if (i*i == n) { res = true; break; } else if (i*i > n) { break; } } return res; } int get_first_squarenumber(int arr[], int sz) { int i; int res = -1; for (int i = 0; i < sz; i++) { if (is_squarenumber(arr[i])) { res = arr[i]; break; } } return res; }
Kết quả:
Leave a Reply
You must be logged in to post a comment.