w3resource

Java Exercises: Test whether there are two integers x and y

Java Basic: Exercise-191 with Solution

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.

Pictorial Presentation:

Java Basic Exercises: Test whether there are two integers x and y

Sample Solution:

Java Code:

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

Flowchart:

Flowchart: Java exercises: Test whether there are two integers x and y

Java Code Editor:

Company:  LinkedIn

Contribute your code and comments through Disqus.

Previous: Write a Java program to find the missing string from two given strings.
Next: Write a Java program to rearrange the alphabets in the order followed by the sum of digits in a given string containing uppercase alphabets and integer digits (from 0 to 9).

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

Java: Anagrams

Generates all anagrams of a string.

public static List<String> anagrams(String input) {
    if (input.length() <= 2) {
        return input.length() == 2
                ? Arrays.asList(input, input.substring(1) + input.substring(0, 1))
                : Collections.singletonList(input);
    }
    return IntStream.range(0, input.length())
            .mapToObj(i -> new SimpleEntry<>(i, input.substring(i, i + 1)))
            .flatMap(entry ->
                    anagrams(input.substring(0, entry.getKey()) + input.substring(entry.getKey() + 1))
                            .stream()
                            .map(s -> entry.getValue() + s))
            .collect(Collectors.toList());
}

Ref: https://bit.ly/3rvAdAK