Suppose there is a method int Multiply(int x,int y). Is it possible for this method to return product of all the integers between x and y without using loop.
For example if the method is called with 3 and 5 : Multiply(3,5) then it should return the product : 3*4*5 = 60.
Interesting question. Please find my attempt to solve this below, The assumption is x is less than or equal to y
public static int multiply(int x, int y){
if(x==y){
return x;
}
if(x == y-1){
return x*y;
}
int product = x*y;
product = product*multiply(x+1,y-1);
return product;
}
With Java 8's streams:
public static int foo (int x, int y){
int high = x > y ? x : y;
int low = x > y ? y : x;
return IntStream.rangeClosed(low, high).reduce(1, Math::multiplyExact);
}
Technically, there are no loops : )
Related
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
Primary test = new Primary();
test.Main();
}
}
class Primary
{
double x;
double y;
double z;
double Small;
double Avg;
int dad;
final int userNumbers = 3;
Scanner in = new Scanner(System.in);
public void Main()
{
System.out.println("Please enter 3 numbers");
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
Primary test = new Primary();
test.Smallest();
test.Average();
System.out.println("The average of the numbers is:" + Avg);
System.out.println("The smallest of the numbers is:" + Small);
}
public void Smallest()
{
if(z < y && z < x)
Small = z;
if (x < z && x < y)
Small = x;
if (y < z && y < x)
Small = y;
}
public void Average()
{
Avg = x + y + z / userNumbers;
}
}
I have no clue what to do since everything ive tried either gives me an error or I'm just not doing it right. I'm not even sure I'm doing what the professor is asking me to do, and he never responds to his emails. If anyone could help me it would be greatly appreciated (And if I'm not doing what my professor is asking please let me know).
Heres his instructions + The assignment on page 248
Around Page 248. Practice Exercise E5.1.You will create one class that has three methods: main(), smallest(), and average(). main() reads the test data values and prints the results. You may want to do this in a loop. smallest() and average() do not read data values or print the results. The main() method reads the data values and prints the results.
Write the following methods and provide a program to test them.
a. double smallest(double x, double y, double z), returning the smallest of the arguments
b. double average(double x, double y, double z), returning the average of the arguments
Here try this....`
let me know how that works
import java.util.ArrayList;
import java.util.Scanner;
package javaapplication17;
public class Question1 {
public static void main(String[] args)
{
double avg, small;
Scanner in = new Scanner(System.in);
System.out.println("Please enter 3 numbers");
double x = in.nextInt();
double y = in.nextInt();
double z = in.nextInt();
//Method calls -----------------------------------
avg = average(x, y, z);
small = smallest(x, y, z);
//Method calls -----------------------------------
System.out.println("The average of the numbers is: " + avg);
System.out.println("The smallest of the numbers is: " + small);
}
public static double smallest(double x, double y, double z)
{
double small = 0;
if(z <= y && z <= x)
small = z;
if (x <= z && x <= y)
small = x;
if (y <= z && y <= x)
small = y;
return small;
}
public static double average(double x, double y, double z)
{
return (x + y + z) / 3.0;
}
}
You do need to learn java to do this. See https://en.wikiversity.org/wiki/Java_Tutorial/Hello_World! and others like it for hints.
To answer the question given to you, you only need one class - you have two. In that class, you need three methods. Two of the methods return values - you have them returning a void. You shouldn't need any field variables in your class.
Structure the class as in the tutorial link. (This isnt' a working answer - you still have to do the homework.)
public class Question1 {
public static void main( String[] args ) {
double x, y, z;
// Add your a loop here to collect your x, y and z
// data and process it
while (true) {
// Collect the data ...
// Call the methods
double smallest = smallest(x, y, z);
double average = average(x, y, z);
// Do something with the results
}
}
public static double smallest(double x, double y, double z) {
double smallValue;
// Add your logic and set smallValue
return smallValue;
}
public static double average(double x, double y, double z) {
// Calculate the average and return that value
// as in the smallest method...
}
}
To test the functions, write another program like the following:
import Question1;
public class TestQuestion1 {
public static void main( String[] args ) {
// Add test code here. Something like
double result = Question1.smallest(1.0, 2.0, 3.0)
// Check that the result is 1.0
// Add other tests - output the results
}
As I have read online that Java is pass by value and a general swap function won't swap the two values. I also read that it's not possible to swap the values of primitive types. I am wondering why the following program works and displays different valies after swap ?
public class swapMe {
public static void main(String[] args) {
int x = 10 , y = 20;
System.out.println("Before");
System.out.println("First number = " + x);
System.out.println("Second number = " + y);
int temp = x;
x = y;
y = temp;
System.out.println("After");
System.out.println("First number = " + x);
System.out.println("Second number = " + y);
}
}
Is it like somewhere, the original values of x = 10 and y = 20 are still stored somewhere and the swapped values displayed are not correct? Please advise. Thanks
Not entirely sure where you're getting that information, but let's take this one at a time.
As I have read online that Java is pass by value and a general swap function won't swap the two values.
Correct...if the expectation of the swap is to happen by virtue of calling a method.
public void swap(int x, int y) {
int tmp = x;
x = y;
y = tmp;
}
// meanwhile, in main
int x = 10;
int y = 20;
swap(x, y);
System.out.println(x); // still prints 10
System.out.println(y); // still prints 20
Incorrect...if the swap happens inside the method and is utilized somehow.
public void swap(int x, int y) {
int tmp = x;
x = y;
y = tmp;
System.out.println(x); // will print 20 from main
System.out.println(y); // will print 10 from main
}
// meanwhile, in main
int x = 10;
int y = 20;
swap(x, y);
System.out.println(x); // still prints 10
System.out.println(y); // still prints 20
I also read that it's not possible to swap the values of primitive types.
No, this is perfectly possible to do. You can always reassign variables.
As to why your example above works, it's because you're holding onto one of the values while you reassign one of its variables. You're basically putting one value to the side while you copy it over.
Slowly...
int x = 10;
int y = 20;
int tmp = x; // tmp = 10
x = y; // x = 20, tmp = 10
y = tmp; x = 20, y = 10; tmp = 10 (but that doesn't matter)
I'm trying to prompt the user to enter 3 numbers. After those numbers are entered, I am to add the highest two numbers. The main method is to handle all print statements and is to call the other method. I'm not allowed to use for loop for this problem. The variables from the main, should be passed down to the other method.
I am not sure why I am unable to call the method from the main. Here is my code:
public class HW {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter three numbers.");
int x = console.nextInt();
int y = console.nextInt();
int z = console.nextInt();
HW.calLargestSum(); //ERROR
HW.calLargestSum(int x, int y, int z); //STILL ERROR
}
public int calLargestSum(int x, int y, int z){
if ( x > y && x > z && y > z )
return x + y;
else if ( y > x && y > z && x > z )
return y + x;
else if ( z > x && z > y && y > x )
return z + y;
return 0;
}
}
You can't call it because you have not instantiated an HW object. Two solutions:
HW hw = new HW();
hw.calLargestSum();
Or make the method static, so that you don't need to instantiate it:
public static int calLargetSum();
Further... ok, so many problems...
HW.calLargestSum(); //ERROR
There is no method calLargestSum(), there is only calLargestSum(int x, int y, int z).
HW.calLargestSum(int x, int y, int z); //STILL ERROR
You need to pass values here. int x is not a value. You need to pass values like:
HW.calLargestSum(1, 2, 3);
Problem
You are making some mistakes when calling the method from main. The non-trivial mistake is that you can't call non-static from static. This happens because if it is not static then it is an instance method. Thus, it requires an instance to access it.
Static Solution
Make your method static. So change your method to:
public static int calLargestSum(int x, int y, int z)
{ ... }
To call the method, you can use:
calLargestSum(1,2,3);
// or in your case.
calLargestSum(x,y,z);
Instance Solution
The other option is to make a new instance of your class (if you don't want it to use static). Like so:
HW hwObj = new HW();
To call use this:
hwObj.calLargestSum(1,2,3);
To See Returned Value/Print
int largest = calLargestSum(x, y, z);
System.out.println(largest);
So I decided to try out Codility. The first task - FrogJmp was ridiculous easy, however to my surprise I scored 44%. Solution, even if correct was obviously unacceptable in terms of performance.
Original solution:
public int solution2(int X, int Y, int D) {
return (int) Math.ceil((float)(Y -X)/D);
}
So I decided to try it with different code, without floating point arithmetic.
public int solution(int X, int Y, int D) {
int diff = Y - X;
if (diff % D == 0)
return diff /D;
else
return diff/D + 1;
}
This time I got 100%. So I wanted to check the performance myself and wrote simple test:
class Solution {
public int solution(int X, int Y, int D) {
int diff = Y - X;
if (diff % D == 0)
return diff /D;
else
return diff/D + 1;
}
public int solution2(int X, int Y, int D) {
return (int) Math.ceil((float)(Y -X)/D);
}
private static Random ran = new Random(System.currentTimeMillis());
public static int getRandom(int a, int b){
return ran.nextInt(b - a + 1) + a;
}
public static void main(String[] args) {
int size = 1000_000;
int max = 1000_000_000;
int[] xs = new int[size];
int[] ys = new int[size];
int[] ds = new int[size];
for (int i = 0; i < size; i++) {
int y = getRandom(1, max);
int x = getRandom(1, y);
int d = getRandom(1, max);
xs[i] = x;
ys[i] = y;
ds[i] = d;
}
long start = System.nanoTime();
Solution sol = new Solution();
for (int i = 0; i < size; i++) {
sol.solution2(xs[i], ys[i], ds[i]);
}
long diff = System.nanoTime() - start;
System.out.println("took: " + diff/1000000 + "ms");
}
}
To my surprise, on my machine the solution 1 takes on average 13ms and solution 2 (the one reported as absolutely ineffective) 10 ms.
What am I missing?
Maybe it has to do something with expected time and space complexity of the tasks.
expected worst-case time complexity is O(1); expected worst-case space
complexity is O(1).
Does not solution 2 have constant time & space complexity?
Also I cannot make sense of this results report for 44% solution:
What does it mean??
100/100 solution in C# I just
using System;
class Solution {
public int solution(int X, int Y, int D) {
return ((Y - X) + D - 1)/D;
}
}
Solution in Java 100/100 and O(1) time complexity.
public int solution(int X, int Y, int D) {
return Double.valueOf(Math.ceil((Y - X) / (double) D)).intValue();
}
Both solutions have O(1) time complexity. The problem is that the first solution is returning wrong answers. The performance tests test the answer as well as the time. Your solution failed probably because of precision issues with the use of floats.
For x = 1, y = 1000000000, d = 1, your first solution gives 1000000000 as an answer, and the second gives
999999999. Changing from (float) to (double) corrects this result.
In these algorithm tests, it's usually a good idea to avoid floating point arithmetic as much as possible to make it easier to get the exact answers for all cases.
OBJECTIVE-C SOLUTION O(1)
Results given by Codility
Task Score: 100%
Correctness: 100%
Performance: 100%
Time Complexity
The worst case time complexity is O(1)
Xcode Solution Here
+(int)solution:(int)x y:(int)y d:(int)d {
/******** Algorithm Explanation ********/
// FACTS
// I realized that the formula: [x+(n*d)] >= y satisfies the required frog jumps
// then, the formula to find the 'n' required jumps is the following:
// n = (y-x)/d
// STEP 1
// Implement the formula in code
// Be careful dealing with the floating point, it should be double
// use the function 'ceil' as a resource to round to the next integer.
double n = ((double)y - (double)x) / (double)d; // O(1)
n = ceil(n);
return (int)n;
}
Solution in Java 100/100 and O(1) time complexity:
public int solution(int X, int Y, int D) {
int diff = Y - X;
int count = diff / D;
if (diff % D > 0) {
count++;
}
return count;
}
JS Solution
Task Score: 100%
Correctness: 100%
Performance: 100%
function solution(X, Y, D) {
return Math.ceil((Y - X) / D);
}
Solution in C#
double result = (Y - X) / (D * 1.0);
return Convert.ToInt32(Math.Ceiling(result));
public static int solution(int X, int Y, int D) {
// write your code in Java SE 8
return (int)Math.round((Y-X)/(double)D);
}
This will also fetch 100%
Tried this one for 100/100
public static int frogJmp(int X, int Y, int D) {
return (int) Math.ceil( (Y-X) / (double)D );
}
Simple O(1) solution in Java:
class Solution {
public int solution(int X, int Y, int D) {
return (Y-X) % D == 0 ? (Y-X) / D : (Y-X) / D + 1;
}
}
Count minimal number of jumps from position X to Y.
public int solution(int X, int Y, int D) {
if (X == Y)
return 0;
else if ((Y - X) % D == 0)
return ((Y - X) / D);
else
return ((Y - X) / D) + 1;
}
First, you should pay attention to divisor which can not be 0 in your case "diff / D", D can not be 0.
Second, in your case "diff = Y - X", if ( diff <= 0 ) then you don't to jump anymore.
Frogjump solution in C
int solution(int X, int Y, int D) {
// write your code in C90
int r=0;
if(Y>X)
{
r=(Y-X)/D;
if((X+(r*D)) < Y) r++;
}
return r;
}
public int solution(int X, int Y, int D) {
// write your code in C# 6.0 with .NET 4.5 (Mono)
double divAll = (Y-X) / (D * 1.0);
double finalRes = (Y-X) % (D * 1.0) > 0 ? (divAll + 1) : divAll;
return (int) finalRes;
}
Here is my 100% / 100% solution
public int solution(int X, int Y, int D) {
double d = D;
return (int) Math.ceil( (Y-X) / d );
}
I just resolved it with perfect score, So this is my answer (java):
static int solution(int X, int Y, int D){
double count=((double)Y-(double)X)/(double) D;
return (int)Math.ceil(count);
}
For the first time i thought it could be rdone by using "While loops" but i got zero performance..
Here is my simple code with detected time complexity of O(1) in Codility.
public int solution(int X, int Y, int D) {
int dev = (Y - X) % D;
if (X == Y)
return 0;
else if (dev == 0)
return (Y - X) / D;
else
return ((Y - X) / D) + 1;
}
Solution 100% in JS
function solution(X, Y, D) {
const distance = Y - X;
if (distance % D === 0) {
return Math.round(distance/D);
}
return Math.floor(distance/D +1);
}
This question already has answers here:
Calculate the power of any exponent (negative or positive)
(5 answers)
Closed 9 years ago.
I need to write a method named pow2 that accepts a real number base and an integer exponent as parameters. It should return the base raised to the given power. Your code should work for both positive and negative exponents. For example, the call pow2(2.0, -2) returns 0.25. Do not use Math.pow in your solution.
This is what I have so far:
public double pow2(double x,int y){
double total=1;
for(int i=1;i<=y;i++){
total*=x;
}
return total;
}
But the problem is when I try to call pow(2.0, -2), it returns me 1.0 instead. How do I implement this method?
You have to branch, depending if you have a negative or a positive value.
Here a version that works with recursion:
public double pow2(double x,int y){
return _pow2(1.0, x, y);
}
private double _pow2(double res, double x, int y) {
if (y < 0) return _pow2(res/x, x, y+1);
if (y > 0) return _pow2(res*x, x, y-1);
return res;
}
If y is too big or too small, then you'll run into a stack overflow, so changing it to a non-recursive function is left to the op.
Edit: about your last question, you set the result to 1.0, the body of the loop is never used because !(1 <= -2), so you return the unmodified result of 1.0
Well, finally if you want to do it in an iterative way, just check first if y is positive or negative.
public double pow2(double x, int y)
{
double total = 1.0;
if(y > 0)
{
for(int i = 1 ; i <= y ; i++)
{
total *= x;
}
}
else
{
for(int i = -1 ; i >= y ; i--)
{
total /= x;
}
}
return total;
}
public static void main(String[] args) {
System.out.println(pow2(2,3));
}
public static double pow2(double x,int y){
double total=1;
for(int i=1;i<=y;i++){
total*=x;
}
return total ;
}
public static double pow2(double x,int y){
double total=1;
if(y>0){
for(int i=1;i<=y;i++){
total*=x;
}
return total;
}
else if (y<0){
double temp=1/x;//this makes 2 as 1/2
y=y*-1; //to have a meaningful iteration if for loop
for(int i=1;i<=y;i++){
total*=temp;
}
return total;
}else
return 1;
}