Question

Java question for two classes: Given the upper limit n as a parameter, the result of...

Java question for two classes:

Given the upper limit n as a parameter, the result of both methods is a
boolean[] array of n elements that reveals the answers to that problem for all natural numbers
below n in one swoop.


public static boolean[] sumOfTwoDistinctSquares(int n)


Determines which natural numbers can be expressed in the form a 2 + b 2 so that a and b are two
distinct positive integers. In the boolean array returned as result, the i :th element should be true
if and only if such a breakdown is possible. The infinite sequence of positive integers that allow
such breakdown begins with 5, 10, 13, 17, 20, 25, 26, 29, 34, 37, 40, 41, 45, 50, 52, ...
You may have previously seen a version of this problem where the breakdown to two distinct
squares was done separately for one number at the time. However, now that we are dealing with
numbers in bulk so that the answers to these numbers are highly interrelated, you might want to
loop through all possible combinations of values of a and b whose squares are less than n and fill
the result table that way, instead of looping through all numbers less than n separately, and for each
such number in turn, try to construct a breakdown as two squares from scratch...


public static boolean[] subtractSquare(int n)


Subtract a square is an interesting impartial game of mental arithmetic for two players. The players
take turns moving from the current number n into any smaller natural number that can be reached
by subtracting some square of a positive integer from n without going below zero. For example, if
the current number n = 15, the player whose turn it is to play must move into one of the three
possible states 14, 11, and 6 of his choice. The player who moves to zero wins the game, since the
opponent cannot make a move.


Using the standard terminology of this sort of impartial combinatorial games, the state 0 in which
no moves are possible is losing or cold . In general, each state is winning or hot if there exists a
move into some cold state, and cold if no such move exists. This rule makes n = 1 to be hot, since
subtracting 1 wins the game, and n = 2 to be cold, since the one possible move from there moves
into a cold state. The infinite sequence of cold states in this game begins with 0, 2, 5, 7, 10, 12, 15,
17, 20, 22, 34, 39, ...


This method should create and return an n -element array of truth values so that the element in
position i is true if the state i is hot, and false if it is cold. Notice that this method should be filling
the result array from left to right, since to determine whether the current position is hot or cold, all
the information needed to make that decision is laid out in the open in the lower-numbered states
whose heat values we have already filled in...

0 0

> Hi guys, I don’t have much to say right now rather than to say thank you to Dr Amber for rescuing me and my family from poverty. I love playing the lottery but winning big is always the issue for me. I will never forget the day I came in contact with Dr Amber whose lottery spell made me a winner of $360,000,000 million dollars cash prize on the jackpot lottery game I played just by giving me sure winning numbers within 3 days to play the lottery game after he prepared the lottery spell for me. My financial status has changed for good and I’ve started to live my dream life after 14 years of playing the lottery. Thank you Dr Amber for I’m very grateful for all you’ve done for me and my family. You can TELEGRAM or call or message Dr Amber via +1 808 481-5132 or email: [email protected] or visit: amberlottotemple.com for more information.

Albert Washington Wed, Apr 20, 2022 6:14 AM

Add a comment Improve this question Transcribed image text
Answer #1

All the explanation is in the code comments. Hope this helps!

Code:

public class Main
{
// required function 1
public static boolean[] sumOfTwoDistinctSquares(int n) {
  
// initialise a boolean array of size n
// the array is 0 indexed and natural numbers start from 1,
// hence the first value is of signifcance
// also the values are evaluted till n-1
// initially all values are false by default
boolean res[] = new boolean[n];
// variables for loop counters
int i=1, j=i+1;
  
// start i loop
while((i*i + j*j) < n) {
  
// set the value at index (i*i + j*j) = true
res[(i*i + j*j)] = true;
  
// update counters
// incease j by 1
j++;
// for overflow, update i and reset j
if((i*i + j*j) >= n) {
i++;
j = i+1;
}
}
// return the boolean array
return res;
}
  
// required function 2
public static boolean[] subtractSquare(int n) {
// initialise a boolean array of size n
// the values are evaluted till n-1, if till n is required use size as n+1
// initially all values are false by default
boolean res[] = new boolean[n];
int move;
  
// loop for all indexes, 0th index is cold by default
for(int i=1; i<n; i++) {
  
// find if ith state can be hot => find a winning move
// loop for hot move till overflow
move = 1;
while((i - move*move) >= 0) {
// the state after move is cold => i is hot state
if(!res[(i - move*move)]) {
res[i] = true;
break;
}
// update move
move++;
}
}
// return results
return res;
}
  
   public static void main(String[] args) {
       // sample run
       // #1
       int n = 55;
       boolean func1[] = sumOfTwoDistinctSquares(n);
       // print results
       System.out.println("Numbers below 55 which are sum of 2 distinct squares:");
       for(int i=0; i<n; i++) {
       if(func1[i])
       System.out.print(i + ", ");
       }
       // #2
       boolean func2[] = subtractSquare(n);
       // print results
       System.out.println("\nCold states are :");
       for(int i=0; i<n; i++) {
       if(!func2[i])
       System.out.print(i + ", ");
       }
   }
}

Sample run:

Numbers below 55 which are sum of 2 distinct squares: 5, 10, 13, 17, 20, 25, 26, 29, 34, 37, 40, 41, 45, 50, 52, 53, Cold sta

Code screenshot:

public class Main { // required function 1 public static boolean() sumofTwoDistinctSquares(int n) { // initialise a boolean a

Add a comment
Know the answer?
Add Answer to:
Java question for two classes: Given the upper limit n as a parameter, the result of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need help with my programming assignment. The language used should be java and the algorithm...

    I need help with my programming assignment. The language used should be java and the algorithm should use search trees so that you play against the computer and he chooses the best move. The tree should have all possibilities on the leaves and you could use recursion to so that it populates itself. The game can be a 3*3 board (no need the make it n*n). Please put comments so that I can understand it. Thanks The game of ‘Walls’...

  • 8.20 Question. Which natural mumbers can be written as the sum of two squares of natural raumbers? State and prove the...

    8.20 Question. Which natural mumbers can be written as the sum of two squares of natural raumbers? State and prove the mast general theorem possible about which natural numbers can be written as the sum of two suares of nutural numbers, and prove it. We give the most gencral result next. 8.21 Theorem. A natural number n can be written as a sum of two squares of natural mumbers if and only if every prime congruent to 3 modulo 4...

  • I need to complete the code by implementing the min function and the alpha betta pruning...

    I need to complete the code by implementing the min function and the alpha betta pruning in order to complete the tic tac toe game using pything. code: # -*- coding: utf-8 -*- """ Created on: @author: """ import random from collections import namedtuple GameState = namedtuple('GameState', 'to_move, utility, board, moves') infinity = float('inf') game_result = { 1:"Player 1 Wins", -1:"Player 2 Wins", 0:"It is a Tie" } class Game: """To create a game, subclass this class and implement actions,...

  • Need help with assignment This assignment involves simulating a lottery drawing. In this type of lottery...

    Need help with assignment This assignment involves simulating a lottery drawing. In this type of lottery game, the player picks a set of numbers. A random drawing of numbers is then made, and the player wins if his/her chosen numbers match the drawn numbers (disregarding the order of the numbers). More specifically, a player picks k distinct numbers between 1 and n (inclusive), as well as one bonus number between 1 and m (inclusive). "Distinct" means that none of the...

  • In Java: I got most of the logic down but I'd like to seen an answer...

    In Java: I got most of the logic down but I'd like to seen an answer that actually prints out the T and H and moves them or those something with an image since I only print out the winner and responses with my own code. This project involves writing a program to simulate a tortoise and hare race. The contenders will each race along a horizontal course that contains at least 50 squares. You may add more if you...

  • A problem that can be solved by the Backtracking technique is the 'Sum-of-Subsets' problem. Given n...

    A problem that can be solved by the Backtracking technique is the 'Sum-of-Subsets' problem. Given n distinct positive numbers (usually called weights), we want to find all possible subsets of these numbers whose sum (or weight) is W. A “binary” state space tree (like in the 0/1 Knapsack problem) can be constructed for this problem, where each level represents one of the n numbers. A left branch indicates that the number is included in the subset, and a right branch...

  • You will write a two-class Java program that implements the Game of 21. This is a...

    You will write a two-class Java program that implements the Game of 21. This is a fairly simple game where a player plays against a “dealer”. The player will receive two and optionally three numbers. Each number is randomly generated in the range 1 to 11 inclusive (in notation: [1,11]). The player’s score is the sum of these numbers. The dealer will receive two random numbers, also in [1,11]. The player wins if its score is greater than the dealer’s...

  • The game lets players know whether they have won, lost, or tied a particular game. Modify...

    The game lets players know whether they have won, lost, or tied a particular game. Modify the game so the players are told the number of games they have won, lost or tied since the start of game play. Implement this change by adding three variables named $wins, $lost, and $ties to the program's Main Script Logic section, assigning each an initial value of 0. Next, modify the analyze_results method by adding programming logic that increments the values of $wins,...

  • 1 Overview For this assignment you are required to write a Java program that plays (n,...

    1 Overview For this assignment you are required to write a Java program that plays (n, k)-tic-tac-toe; (n, k)-tic- tac-toe is played on a board of size n x n and to win the game a player needs to put k symbols on adjacent positions of the same row, column, or diagonal. The program will play against a human opponent. You will be given code for displaying the gameboard on the screen. 2 The Algorithm for Playing (n, k)-Tic-Tac-Toe The...

  • Correct answer for this Java problem will get thumbs up and eternal thanks Problem Description Over...

    Correct answer for this Java problem will get thumbs up and eternal thanks Problem Description Over the course of this semester you will write a chess game database that will import chess games in PGN (http://www.saremba.de/chessgml/standards/pgn/pgn- complete.htm) format. As a first step you will write code to read PGN games and resolve board positions. Solution Description Write a class called PgnReader that contains the following public static methods: tagValue takes two String arguments: a tag name and a String which...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT