Q:

Write a Java program to test whether there are two integers x and y such that x^2 + y^2 is equal to a given positive number

0

Write a Java program to test whether there are two integers x and y such that x^2 + y^2 is equal to a given positive number

Expected Output:

Input a positive integer:  25
Is 25 sum of two square numbers? true

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

import java.util.*;
public class Solution {  
   public static void main(String[] args) {
        Scanner in = new Scanner(System.in);	
        System.out.print("Input a positive integer: ");
        int n = in.nextInt(); 
		if (n>0)
		{
           System.out.print("Is "+n+" sum of two square numbers? "+sum_of_square_numbers(n));
		}  		
    }

 public static boolean sum_of_square_numbers(int n) {
        int left_num = 0, right_num = (int) Math.sqrt(n);
        while (left_num <= right_num) {
            if (left_num * left_num + right_num * right_num == n) {
                return true;
            } else if (left_num * left_num + right_num * right_num < n) {
                left_num++;
            } else {
                right_num--;
            }
        }
        return false;
    }
}

Sample Output:

Input a positive integer:  25
Is 25 sum of two square numbers? true

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now