I have integers a, b, c, d. I want to design a program which will output me the average of the numbers after discarding the highest and the lowest numbers. So if I have input 3 7 5 3, I would want output 4. I have to do this without using the math library, loops or arrays. My code is below. It runs but gives the wrong output. What am I doing wrong?
public class average{
public static void main(String[] args) {
int a, b, c, d;
a = Integer.valueOf(args[0]);
b = Integer.valueOf(args[1]);
c = Integer.valueOf(args[2]);
d = Integer.valueOf(args[3]);
if ((a>b)&&(a>c)&&(a>d))
{a= 0;
}
if ((a<b)&&(a<c)&&(a<d))
{a= 0;
}
if ((b>a)&&(b>c)&&(b>d))
{b=0;
}
if ((b<a)&&(b<c)&&(b<d))
{b=0;
}
if ((c>a)&&(c>b)&&(c>d))
{c=0;
}
if ((c<a)&&(c<b)&&(c<d))
{c=0;
}
if ((d>a)&&(d>b)&&(d>c))
{d=0;
}
if ((d<a)&&(d<b)&&(d<c))
{d=0;
}
int x;
// x is the average of all the numbers excluding the largest and the smallest
x= ((a+b+c+d)/2);
System.out.println(x);
}
}
in your input example 3 3 5 7, a and b are equal. but your code only compares for less than (<) value, so when your code execution reaches line “x= ((a+b+c+d)/2);” you have a=3, b=3 and c=5 which results into x =5.
Hope this explains why you are not getting expected result.
The if conditions you provided do not work as expected when two or more numbers are same, which is explained clearly by Rai.
You can store the minimum and maximum values in min and max variables.
int min = a, max = a;
if(b > max)
{
max = b;
}
if(c > max)
{
max = c;
}
if(d > max)
{
max = d;
}
Similarly for min.
And when you are summing the numbers for average, just add all four numbers and subtract the sum of min and max.
I hope it is clear enough.
A quick and short solution where there is no loop, no arrays and math library is not used:
public static void main(String[] args) {
args = new String[] {"3", "7", "5", "3"};
int a = Integer.valueOf(args[0]);
int b = Integer.valueOf(args[1]);
int c = Integer.valueOf(args[2]);
int d = Integer.valueOf(args[3]);
List<Integer> numbers = new ArrayList<>();
numbers.add(a);
numbers.add(b);
numbers.add(c);
numbers.add(d);
Integer min = numbers.stream().min(Integer::compare).get();
Integer max = numbers.stream().max(Integer::compare).get();
numbers.remove(min);
numbers.remove(max);
int average = (numbers.get(0) + numbers.get(1)) / 2;
System.out.println("average: " + average);
}
Related
I have got a little problem—I need to prepare program that (step by step information):
1)Gets from user two integers a and b and stop when b>a
2)Sum the products off all numbers in range < a, b > that digits are prime numbers
Example:
Input: 10, 15,
Output: 2340
(because 12*13*15 = 2340
2, 3 and 5 are prime numbers)
I feel like I stuck—I have got only a sum of the numbers (not the product) and not the prime but all of them.
public class Ex4 {
static int getNmbs() {
System.out.println("Enter number:");
Scanner sc = new Scanner(System.in);
return sc.nextInt();
}
public static int getSum(int a, int b) {
if (a > b)
return 0;
else
return a + getSum(a + 1, b);
}
public static void main(String[] args) {
int a = getNmbs();
int b = getNmbs();
int c =getSum(a,b);
System.out.println(c);
}
}
In order to solve this problem, you need to think of the step by step process:
First, accept two integer inputs, a and b.
Declare a variable to hold your product (the answer) and initialize it at 1. (If you initialize it at 0, then you will always get 0)
Now, assuming a < b, check to see if the digits of a are prime. IF it is, multiply your product by it and increment a. If it isn't, just increment a.
Rinse and repeat until a > b. And return the final product.
The trick here is going to be figuring out a way to check if the digits of a number are prime. I suggest using modulo division in increments of powers of 10 (for those more mathematically inclined) or converting the integer to a String and checking each character (using toCharArray).
Hope this helps!
This is a non recursive approach.
static boolean isProductPrime(int num){
int tmp = num % 10;
if( tmp < 2) return false;
for(int i = 2; i*i <= tmp; i++) //Instead of Math.SQRT
if(tmp % i == 0) return false;
return true;
}
public static void main(String [] args) {
Scanner myScanner = new Scanner(System.in);
int a = myScanner.nextInt();
int b = myScanner.nextInt();
int ans = 1;
for(int i = a ; i <= b ; i++){
if(isProductPrime(i))
ans *=i;
}
if( b < a)
ans = 0;
System.out.println(ans);
}
I'm writing a code for an assignment for school but it requires me to compare two int values. For example, if you have the number 123 and the other number is 321, they have the same digits but are in different orders. Is there easy way of comparing them or do i have to make them into a string and compare them as string types? if its the latter, how could i compare two strings? Is there any way of doing this without an array?
By comparing int values, if you mean greater than, less than or equal you can do that like so.
int a = 123, b= 321;
if(a > b)
//a is greater than b (b is less than a)
if(a == b)
// a is equal to b
if(a < b)
// a is less than b (b is greater)
Could use some clarification, if you want to check if the number is reversed like you said in an example its called a palindrome.
You could reverse a number in the following if you had experience with loops and modulo(the %) in the following snippet.
int r = 0;
while(number != 0){
r = r * 10 + number % 10;
number /= 10; }
return r;
r would be that number reversed. If you input let's say 123 you would get 321 back, then you could compare it to the other to see if its just the reverse.
Let me know if you have any more questions and I'll try to answer!
To check if a number is arbitrarily mixed and not reversed to winning number, you could try the following.
Two numbers a and b, a is the winning number and b is the number the user chose.
a is 251 and b is 521.
You could do this on each number to separate them.
int p1,p2,p3;
p1 = num % 10;
p2 = num / 10 % 10;
p3 = num / 100 % 10;
This would separate ex. 251 into 2, 5, and then 1. Then you could add them as so doing the same process for the second. sum is p1 + p2 + p3 and sum2 is p4 + p5 + p6 for the second number. Provided the numbers are not reversed. Use the thing I mentioned before for that case to check if they are flipped.
if(sum == sum2)
//Numbers are mixed but you won!
This should work.
Certainly not the fastest solution, but the code is short and easy to understand.
public boolean arePalindromes(int a, int b){
//convert them to char arrays for easy sorting
char[] aryA = String.valueOf(a).toCharArray();
char[] aryB = String.valueOf(b).toCharArray();
//sort them
Collections.sort(aryA);
Collections.sort(aryB);
//put them back to strings for easy comparison
String strA = new String(aryA);
String strB = new String(aryB);
//compare
return strA.equals(strB);
}
Please try the following code (I have tested it), of which idea is borrowed from here and here. This solution still uses array.
public class CompareInt {
public static void main(String[] args) {
System.out.println(containSameDigits(123, 123));
System.out.println(containSameDigits(123, 321));
System.out.println(containSameDigits(123, 132));
System.out.println(containSameDigits(123, 323));
System.out.println(containSameDigits(123, 124));
System.out.println(containSameDigits(123, 111));
}
public static boolean containSameDigits(int x, int y) {
String xSorted = getSortedString(x);
String ySorted = getSortedString(y);
return xSorted.equalsIgnoreCase(ySorted);
}
public static String getSortedString(int x) {
String xSorted = "";
for (int digit = 0; digit < 9; digit++) {
for (int temp = x; temp > 0; temp /= 10) {
if (temp % 10 == digit) {
xSorted += digit;
}
}
}
return xSorted;
}
}
Output:
true
true
true
false
false
false
So I am not very good at it yet at all (understatement). I am trying to solve problems in the Euler project, and I am already stuck on 2.
Each new term in the Fibonacci sequence is generated by adding the previous 2 terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
Here is my code which I have repeatedly tried to fix:
(I think there is something wrong with the for loop logic.)
public class tesy {
public static void main(String args[]) {
int fib = 0;
int tot = 0;
int total = 0;
for (fib = 0; tot < 4000000; fib++) {
tot = fib + (fib + 1);
if (tot % 2 == 0) {
total = tot + total;
}
}
System.out.println(total);
}
}
Your logic is erroneous in couple of ways,
tot = fib + (fib + 1); /** This will always be `(2*fib + 1)` and `fib` is getting
incremented by 1 each time. You have no reference to the previous two terms of the
sequence. **/
Try the below logic instead.
class Fibonacci
{
public static void main (String[] args)
{
int fiboFirst = 1;
int fiboSecond =2;
int fib = 0;
int sum = 0;
while(fiboSecond < 4000000)
{
// This will calculate the current term of the sequence
fib = fiboFirst + fiboSecond;
// Below two lines will update fib[i] and fib[i - 1] terms
// for the next loop iteration.
fiboFirst = fiboSecond; // fib[i]
fiboSecond = fib; // fib[i -1]
if (fib % 2 == 0)
{
sum = sum + fib;
}
}
System.out.println(sum+2);
}
}
Explanation
Here fiboFirst is equivalent to F[n] and fiboSecond is equivalent
to F[n - 1] in the Fibonacci sequence definition. In each iteration,
those two values should be replaced, in order to be used in the next
iteration. That is why I have these two lines,
fiboFirst = fiboSecond; // fib[i]
fiboSecond = fib; // fib[i -1]
HERE is the execution of the above program
You don't seem to be following the actual equation used to generate a fibonacci sequence, therefore there is no (obvious) way of fixing your code.
int fibA = 1, fibB = 2, total = 0;
while(fibB <= 4000000) {
// Add to the total, set fibA to fibB and get the next value in the sequence.
if(fibB % 2 == 0) total += fibB;
int temp = fibA;
fibA = fibB;
fibB = fibB + temp;
}
The above code should find the sum of all values less than or equal to 4000000
Here is a solution that uses BigInteger. Please verify the results.
public class Fibonacci{
public static void main(String[] args) {
BigInteger r = fibonacciEvenSum();
System.out.println(r);
}
public static BigInteger fibonacciEvenSum(){
int f = 1;
int s = 2;
int mn4 = 4000000;
BigInteger sum = BigInteger.valueOf(0);
while(s <= mn4){
if(s % 2 == 0){
sum = sum.add(BigInteger.valueOf(s));
}
f = f + s;
s = s + f;
}
return sum;
}
}
Before writing a program like this, you should first think of what's underlying this program. You should first understand how to generate a Fibonacci series before graduating on to doing something with the series. I'll give you my solution so that you can understand.
class euler2 {
public static void main(String[] args) {
int a = 0, b = 1; /* the first elements of Fibonacci series are generally
thought to be 0 and 1. Therefore the series is 0, 1, 1, 2, 3... .
I've initialized first and second elements such */
double sum = 0; // The initial sum is zero of course.
while (b < 4000000) /* since b is the second term, it will be our control variable.
This wouldn't let us consider values above 4M. */
{
int ob = b; // to swap the values of a and b.
b = a + b; // generating next in the series.
a = ob; // a is now the older value of b since b is now a + b.
if (b % 2 == 0) // if b is even
sum += b; // we add it to the sum
}
System.out.println(sum); // and now we just print the sum
}
}
Hope this helped!
i want to print all armstrong number between 1 to 1000 in a textfield using awt or swing but i only get last value by my code .So pls help me
public void actionPerformed(ActionEvent e)
{
String s1=tf.getText();
int n1=Integer.parseInt(s1);
for(int n=0;n<10000;n++)
{
int sum=0;
int number=n;
int original=number;
while(number>0)
{
int r=number%10;
sum+=r*r*r;
number=number/10;
}
if(sum==original)
{
tf1.setText(String.valueOf(original[i]));
}
}
}
For those who don't know, an Armstrong number (or narcissistic number) is a number with n digits that is equal to the sum of each of its digits to the nth power.
(x1*10(n-1))+(x1*10(n-2))...+(x1*10(n-n)) = (x1)n+(x2)n...+(xn)n
This means that if the number is 1 digit, the power will be 1.
Therefore there are 10 1 digit numbers that are Armstrong numbers:
0 = 01
1 = 11
2 = 21
3 = 31
4 = 41
5 = 51
6 = 61
7 = 71
8 = 81
9 = 91
Your code, as written, will not identify any of those numbers as Armstrong numbers.
Your code will also incorrectly identify some numbers as 4 digit Armstrong numbers because you only look for the the cubes (3rd power) of your numbers not the 4th power.
(You don't have to worry about twos because there are no two digit Armstrong numbers)
In order to correctly determine all the possible Armstrong numbers between 1 and 10000, you need to write a "power" loop that finds the nth power of a number by multiplying the number n times.
This would look something like:
//... beginning of your original function
//added a string to hold all the values before printing
string holder = "";
for(int n=0;n<10000;n++){
int sum=0;
//n=original you had duplicate variables (just use n as original)
int number = n;
//while there are still digits left
while(number>0){
//get the smallest digit
int r=number%10;
//----------"Power" loop-----------
int foo = n;
//once smaller than 10, it's only a power of 1 (which is itself)
while(foo>=10){
//this means foo = foo/10
foo /= 10;
//this means r = r*r
r*=r;
}
//this means sum = sum+r
sum += r;
//you should have the hang of it by now
number/=10;
}
//if the sum equals the original number
if(sum==n){
//put that number into the end of a string (separated by newlines `\n`)
holder+=n+"\n";
}
}
//All done, so set the text box value
tf1.setText(holder);
//... whatever code you want to finish up
This should also take care of your problem with the textBox getting overwritten each time. By saving the numbers into a string and then printing all of them at once, only once (no overwriting), you'll get better results.
You always set the current found value. But you should set the previous found values + current found value.
tf1.setText(String.valueOf(original));
But more performant would be to use a stringbuilder object and append the result each time and set this value to the textfield outside the loop.
public void actionPerformed(ActionEvent e)
{
StringBuilder s = new StringBuilder ();
for(int n=0;n<10000;n++)
{
int sum=0;
int number=n;
int original=number;
while(number>0)
{
int r=number%10;
sum+=r*r*r;
number=number/10;
}
if(sum==original)
{
s.append(original + " ");
}
}
tf1.setText (stringBuilder.toString ());
}
Easy, all you do is change the setText() method of the TextField1 component with append().
It works! The remaining will do! Try it once.
public void actionPerformed(ActionEvent e)
{
String s1=tf.getText();
int n1=Integer.parseInt(s1);
for(int n=0;n<10000;n++)
{
int sum=0;
int number=n;
int original=number;
while(number>0)
{
int r=number%10;
sum+=r*r*r;
number=number/10;
}
if(sum==original)
{
tf1.append(String.valueOf(original[i] + " "));
}
}
}
Very simple program in C to list all armstrong number between 1 to 1000000.
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
long a = 1, c=0, b, e, f, d = 0,g=0,p,j,count=0;
printf("All armstron number between 1 and 1000000 is listed below!\n");
while (c <= 1000000)
{
j = c;
if (j >= 10)
{
while (j >= 10)
{
j = j / 10;
g++;
}
}
p = g + 1;
g = 0;
a = c;
f = a;
while (a >= 10)
{
b = a % 10;
d = d + pow(b,p);
a = a / 10;
}
e = pow(a,p) + d;
d = 0;
if (e == f)
{
count++;
printf("%ld\t",count );
printf("%ld\n", f);
}
c++;
}
getch();
}
I just gave a coding interview on codility
I was asked the to implement the following, but i was not able to finish it in 20 minutes, now I am here to get ideas form this community
Write a function public int whole_cubes_count ( int A,int B ) where it should return whole cubes within the range
For example if A=8 and B=65, all the possible cubes in the range are 2^3 =8 , 3^3 =27 and 4^3=64, so the function should return count 3
I was not able to figure out how to identify a number as whole cube. How do I solve this problem?
A and B can have range from [-20000 to 20000]
This is what I tried
import java.util.Scanner;
class Solution1 {
public int whole_cubes_count ( int A,int B ) {
int count =0;
while(A<=B)
{
double v = Math.pow(A, 1 / 3); // << What goes here?
System.out.println(v);
if (v<=B)
{
count=count+1;
}
A =A +1;
}
return count ;
}
public static void main(String[] args)
{
System.out.println("Enter 1st Number");
Scanner scan = new Scanner(System.in);
int s1 = scan.nextInt();
System.out.println("Enter 2nd Number");
//Scanner scan = new Scanner(System.in);
int s2 = scan.nextInt();
Solution1 n = new Solution1();
System.out.println(n.whole_cubes_count (s1,s2));
}
}
Down and dirty, that's what I say.
If you only have 20 minutes, then they shouldn't expect super-optimized code. So don't even try. Play to the constraints of the system which say only +20,000 to -20,000 as the range. You know the cube values have to be within 27, since 27 * 27 * 27 = 19683.
public int whole_cubes_count(int a, int b) {
int count = 0;
int cube;
for (int x = -27; x <= 27; x++) {
cube = x * x * x;
if ((cube >= a) && (cube <= b))
count++;
}
return count;
}
For the positive cubes:
i = 1
while i^3 < max
++i
Similarly for the negative cubes but with an absolute value in the comparison.
To make this more general, you need to find the value of i where i^3 >= min, in the case that both min and max are positive. A similar solution works if both min and max are negative.
Well, it can be computed with O(1) complexity, we will need to find the largest cube that fits into the range, and the smallest one. All those that are between will obviously also be inside.
def n_cubes(A, B):
a_cr = int(math.ceil(cube_root(A)))
b_cr = int(math.floor(cube_root(B)))
if b_cr >= a_cr:
return b_cr - a_cr + 1
return 0
just make sure your cube_root returns integers for actual cubes. Complete solution as gist https://gist.github.com/tymofij/9035744
int countNoOfCubes(int a, int b) {
int count = 0;
for (int startsCube = (int) Math.ceil(Math.cbrt(a)); Math.pow(
startsCube, 3.0) <= b; startsCube++) {
count++;
}
return count;
}
The solution suggested by #Tim is faster than the one provided by #Erick, especially when A...B range increased.
Let me quote the ground from github here:
"one can notice that x³ > y³ for any x > y. (that is called monotonic function)
therefore for any x that lies in ∛A ≤ x ≤ ∛B, cube would fit: A ≤ x³ ≤ B
So to get number of cubes which lie within A..B, you can simply count number of integers between ∛A and ∛B. And number of integers between two numbers is their difference."
It seems perfectly correct, isn't it? It works for any power, not only for cube.
Here is my port of cube_root method for java:
/*
* make sure your cube_root returns integers for actual cubes
*/
static double cubeRoot(int x) {
//negative number cannot be raised to a fractional power
double res = Math.copySign(Math.pow(Math.abs(x), (1.0d/3)) , x);
long rounded_res = symmetricRound(res);
if (rounded_res * rounded_res * rounded_res == x)
return rounded_res;
else
return res;
}
private static long symmetricRound( double d ) {
return d < 0 ? - Math.round( -d ) : Math.round( d );
}
I am aware of Math.cbrt in java but with Math.pow approach it is easy to generalize the solution for other exponents.