Problem in code and need a short code to solve problem - java

fist thing first , the code :
package com.company;
import java.util.Scanner;
public class index {
public static void main (String[] args)
{
System.out.println("enter any three digit number ");
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
//let a= 2 7 4
int b= a%10;//4
int c=a/10;//27
int d= c%10;//7
int e=c/10;//2
//e=first num;
//d=middle num;
//b= last num ;
// for searching the greatest number
if (d>e && d>b )
System.out.printf(" the greatest number is %d%d%d",d,e,b);
else if(e>d && e>b )
System.out.printf(" the greatest number is %d%d%d",e,d,b);
else if (b>e && b>d )
System.out.printf(" the greatest number is %d%d%d",b,e,d);
// for the smallest number
else if(d<e && d<b && b>e)
System.out.printf(" the smallest number is %d%d%d",b,e,d);
else if(d<e && d<b && e>b)
System.out.printf(" the smallest number is %d%d%d",e,b,d);
else if (e<d && e<b && b>d)
System.out.printf(" the smallest number is %d%d%d",b,d,e);
else if(e<d && e<b && d>b)
System.out.printf(" the smallest number is %d%d%d",d,b,e);
else if (b<e && b<d && e>d)
System.out.printf(" the smallest number is %d%d%d",e,d,b);
else
System.out.printf(" the smallest number is %d%d%d",d,e,b);
}
}
now the problem:
this code is make to take number from the user as the input **of any three digit number ** and change it to the greatest number and smallest number ,
for example:
input number =274
output :
greatest number=742
smallest number=247
the above code is giving the greatest number but not the smallest number and the code is very lengthy ,
my output:
enter any three digit number
546
the greatest number is 654
so please help ,any error in code and if there is any short code then please help

I think that the problem is in the way of solution. As for me that is better to use some array or list and sort it. Something like that
public static void main (String[] args)
{
System.out.println("enter any three digit number ");
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int[] array = new int[3];
for (int i = 0; i < 3; i++) {
array[i] = a % 10;
a = a / 10;
}
Arrays.sort(array);
int smallest = 0;
int greatest = 0;
for (int i = 0; i < 3; i++) {
smallest += array[i];
if (i != 2) {
smallest *= 10;
}
}
for (int i = 2; i > -1; i--) {
greatest += array[i];
if (i != 0) {
greatest *= 10;
}
}
System.out.println(Arrays.toString(array));
System.out.println(smallest);
System.out.println(greatest);
}

May I suggest a whole different approach?
void printGreatestAndSmallest(int number) {
char[] digits = String.valueOf(number).toCharArray();
Arrays.sort(digits);
String smallest = new String(digits);
String greatest = new StringBuilder(smallest).reverse().toString();
System.out.println("Greatest number is " + greatest);
System.out.println("Smallest number is " + smallest);
}
What happens here, is that we convert the digits to a char[], which can be sorted using Arrays.sort(...). This way, the smallest digit comes in front, the largest at the end. The char[] is converted back to a string with the String(char[]) constructor.
That is the smallest value. The largest value is the reverse of it! We can get the largest number using StringBuilder's reverse() method.
Note that this code cannot handle negative numbers.
The problem with your current approach is that it contains a lot of repetitions, and is not quite flexible; it is bound to an input of exactly three digits.
In order to fix the issue your are facing, remove the else keyword from the line else if(d<e && d<b && b>e). Each if-elseif-else statement only executes a single branch, but you need two branches to be executed, one for the smallest number, and one for the greatest number.
Further:
Use descriptive variable names. You have a comment in your code:
//e=first num;
//d=middle num;
//b= last num ;
but why don't you rename e, d and b to firstDigit, middleDigit and lastDigit respectively?
Follow the Java Naming Conventions. Variable and method names are written in camelCase, and class names in PascalCase. So class index should be class Index. Also make sure to rename index.java to Index.java.
You are defining variables with almost the same function: in your case firstNum, middleNum and lastNum. They all allow to store a specific digit of the input number. In such a case, you should use an array instead of separate variables. Loops work well with arrays.
If your code somehow iterates over all possible permutations of some collection, using if-else statements, that is probably not the best way.
For example:
if (d>e && d>b )
else if(e>d && e>b )
else if (b>e && b>d )
You should ask yourself: should these digits be in a certain order? The answer here is yes, they need to be sorted from low to high (and high to low). In that case, you probably want to sort them.

Related

Converting multiple strings into one then parsing to int

I know this is not the simplest way to find a palindrome...but I was hoping someone might tell me if there is a way to convert multiple strings of integers into a single int. Maybe that builds a single string from others? Below I have an output that reverses the number you input. However, it comes out as a string of separate integers. Would I be able to typecast this into a single int then bool it against the original number somehow?
If I overlooked a topic similar to this, I'm sorry. I checked around and didn't find one that clearly solved my issue.
import java.util.Scanner;
public class Palindrone{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 2 and 6 digits:");
int num1 = input.nextInt();
int rev = 0;
//find last number
if(num1 >= 10){
rev = num1%10;
System.out.print(rev);
}
//find 2nd to last and 3rd from last
if(num1 >= 100){
rev = num1%100/10;
System.out.print(rev);
rev = num1%1000/100;
System.out.print(rev);
}
//find 4th from last
if(num1 >= 1000){
rev = num1%10000/1000;
System.out.print(rev);
}
//find 5th
if(num1 >= 10000){
rev = num1%100000/10000;
System.out.print(rev);
}
//find 6th
if(num1 >= 100000){
rev = num1%1000000/100000;
System.out.print(rev);
}
}
}
I'm trying to go from printing string (int rev)(int rev)(int rev)(int rev) to
one solid string then converting to int. Then if(newInt == num1) run statement.
You could go this way without the headache of string-int conversion:
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 2 and 6 digits: ");
String number = input.next();
System.out.println(new StringBuilder(number).reverse()); //prints reverse number
Easy, the following method uses Guava to perform the various steps:
public static boolean palindrome(int number) {
// Split into an array of digits and reverse
List<String> digits = Lists.transform(
Lists.reverse(
Lists.transform(
Lists.transform(
Lists.charactersOf(Integer.toString(number)),
Functions.toStringFunction()),
Ints.stringConverter())),
Ints.stringConverter().reverse());
// Join the strings and parse to an integer
int result = Integer.parseInt(Joiner.on("").join(digits));
// And check if a palindrome
return (result == number);
}
So, you could use the same technique with your code, if you create an empty list at the beginning, and add each parsed integer to the end of the list. However the way you are using the modulus operator with the fixed sequence of numbers multiplying by 10 each time is limiting. Instead, if you want to use this parsing method, consider a loop instead:
List<Integer> digits = Lists.newArrayList();
while (number > 10) {
int digit = number % 10;
digits.add(digit);
number /= 10;
}
Then reverse and transform back to a list of strings, and convert to an integer:
List<String> strings = Lists.transform(
Lists.reverse(digits),
Ints.stringConverter().reverse());
int result = Integer.parseInt(Joiner.on("").join(strings));
And again just check for equality with the original number.

Output for finding Sum of the subarray do not come as Expected

Prateek wants to give a party to his N friends on his birthday, where each friend is numbered from 1 to N. His friends are asking for a gift to come to the party, instead of giving him one. The cost of the gifts are given in the array Value where ith friend asks for a gift which has a cost Costi.
But, Prateek has only X amount of money to spend on gifts and he wants to invite his friends which are in continuous range such that sum of the cost of the gifts of those friends will be exactly equal to X.
If he can invite his friends, who can satisfy the above condition then, print YES otherwise print NO.
Input:
The first line contains a single integer T, denoting the number of test cases. In each test case, the following input will be present: - The next line contains two space-separated integers N and X, where N represents the number of friends and X represents amount of money which Prateek can spend on gifts.
- Next N line contains N integers, where ith line contains ith integer, which represents the Costi .
Ouput
Output exactly T lines, each containing the answer to the corresponding test case .
Constraints:
1 <= T <= 10
1 <= N , Costi <= 106
1 <= X <= 1012
Sample Input(Plaintext Link)
1
5 12
1
3
4
5
2
Sample Output(Plaintext Link)
YES
MyApproach
I followed what is said to take the input and took the subarry sum for every element.But I am not getting Expected output.
public static void counCondition()
{
boolean b1=false;
int Sum=0;
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
for(int i=1;i<=T;i++)
{
sc.nextLine();
String nextLine = sc.nextLine(); //#Edited my mistake
String[] input = nextLine.split("\\s+");
int p = Integer.parseInt(input[0]);
int c = Integer.parseInt(input[1]);
int Cost[]=new int[p];
for(int j=0;j<Cost.length;j++)
{
Cost[j]=sc.nextInt();
}
for(int k=0;k<Cost.length;k++)
{
Sum=0;
for(int l=k;l<p;l++)
{
Sum=Sum+Cost[l];
if(Sum>c)
{
break;
}
else if(Sum==c)
{
b1=true;
break;
}
}
}
if(b1==true)
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
sc.close();
}
//#Edit Output is still the same.
**ActualInput** **ExpectedInput**
1 1
5 12 5 12
1 1
3 3
4 4
5 5
2 2
6
7
8
9
2
**ActualOutput** Expected Output(Plaintext Link)
NO YES
I am not expecting this output.
Can anyone guide me why?
Once you have got the individual cost in the Cost array.
Here is the logic to get continous sum equal to max sum.
Maintain a start index variable telling from where continous sequence is starting. In the start it should be zero index.
Maintain sum variable to track the total sum.
Run a for loop from zero to endIndex.
if sum less than max sum
Add Cost[i] to sum.
else if sum equals max sum, break the for loop
else if sum greater than max sum
Now remove elements from startIndex till sum again becomes less or equal to max sum using while loop.
while(sum > maxSum)
sum = sum - cost[startIndex]
increment startIndex
while loop finished
if sum equals maxsum, break the loop you got your answer
else continue the outer for loop.
The idea of this logic is to keep removing elements from start from the sum whenever sum increases the maxsum.
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t>0)
{
int n=sc.nextInt();
long x=sc.nextLong();
long[] money=new long[n];
for(int i=0;i<n;i++)
{
money[i]=sc.nextInt();
}
long sum;
int c=0;
sum=money[0];
for(int i=1;i<n;i++)
{
if(sum<x)
sum=sum+money[i];
else if(sum==x)
break;
while(sum>x)
{
sum=sum-money[c];
c++;
}
}
if(sum==x)
System.out.println("YES");
else
System.out.println("NO");
t--;
}
here http://jayarampandava.blogspot.in/2015_10_01_archive.html
you can find the actual solution
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at app.HackerEarth25Dec2015.counCondition(HackerEarth25Dec2015.java:18)
The exception is occurring because you are calling next() method not the nextLine(). The next() method return the next token which 5 here not the complete line.
Also I would suggest you to use the nextInt() from the Scanner instead of getting the String and splitting and parsing it. That would be a cleaner way of doing things.
int p = sc.nextInt();
int c = sc.nextInt();
Also your logic is also not correct. I hope you will find the logical error and fix it.
You can use the below code for fixing the issue.
sc.nextLine(); // This is to read the `\n` left from previous `nextInt()`
String nextLine = sc.nextLine();
String[] input = nextLine.split("\\s+");

Output amount of primes in array

I'm kind of a newbie at Java, and not very good at it. It's a trial and error process for me.
I'm working on a Java program to output the amount of primes in an array. I can get it to output the primes, but I want to also output the quantity of primes. I tried to add each prime to an array list titled "primes" then return "primes.size()" at the end of my program. It doesn't work as intended. The count is actually off. When I create an array of 5 numbers, it outputs 3 primes, 2, 3, and 5. But then it says I have 4 primes. I think it might be counting 1 as a prime. Because when I create an array of 20, the prime numbers output 2,3,5,7,11,13,17 and 19. Then it says the total prime numbers = 9. It should be 8 though.
Here's my code
public class Prime {
public static void main(String[] args) {
int index = 0;
Scanner scan = new Scanner(System. in );
System.out.println("How big would you like the array? ");
int num = scan.nextInt();
int[] array = new int[num];
ArrayList < Integer > primes = new ArrayList < Integer > ();
//System.out.println("How Many threads? ");
//int nThreads = scan.nextInt(); // Create variable 'n' to handle whatever integer the user specifies. nextInt() is used for the scanner to expect and Int.
//Thread[] thread = new Thread[nThreads];
for (int n = 1; n <= array.length; n++) {
boolean prime = true;
for (int j = 2; j < n; j++) {
if (n % j == 0) {
prime = false;
break;
}
}
if (prime) {
primes.add(n);
}
if (prime && n != 1) {
System.out.println(n + "");
}
}
System.out.println("Total Prime numbers = " + primes.size());
System.out.println("Prime Numbers within " + array.length);
}
}
Forgive the sloppiness of it. I actually plan on adding multithreading to it, but I wanted to get this down first.
Any help would be greatly appreciated. Thanks.
You have included 1 in your array of primes, because you started the n for loop at 1. You don't print it because of the final if statement, but it's there in the ArrayList.
Start your n for loop with n = 2. As a consequence, you won't need the final if statement, because n won't be 1 ever. You could print the prime at the same time as you add it to the ArrayList.

Sum of Digits in Java

import java.util.Scanner;
public class CubesSum {
public static void main (String [] args){
int input;
System.out.println("Enter a positive integer:");
Scanner in = new Scanner(System.in);
input = in.nextInt();
int number = input; //number is a temp variable
int sum = 0;
while(number>0){
int t= number%10;
sum += t*t*t;
number = number/10;
}
System.out.println("The sum of the cubes of the digits is:" +sum);
}
}
Okay so I'm using a while loop. For part B which is to modify to determine what integers of two, three, and four digits are equal to the sum of the cubes of their digits. So for example, 371 = 3³+7³+1³. Can someone tell me how to do it? I need to wrap a for loop around my while loop...
Take the part of your code that computes the sum of the cubes of the digits of a number, and make that a function:
int sumOfCubedDigits(int number) {
int sum = 0;
// compute sum from number
return sum;
}
Then, loop through all the 2-to-4 digit numbers and check whether they equal the sum of the cubes of their digits:
for (int n = 10; n < 10000; n++) {
if (n == sumOfCubedDigits(n)) {
// do whatever with n
}
}
You could keep the sum-of-cubed-digits computation inside the for loop if you want, but it'd be a bit less readable.
Okay, so it looks like you haven't learned about function definitions yet. I shouldn't have assumed. Let's do it with a nested loop, then.
As you said, you need to wrap a for loop around your while. We need to consider all 2-to-4 digit numbers, so our loop will start at the first 2-digit number and end when it reaches the first 5-digit number:
for (int n = 10; n < 10000; n++) {
// More code will go here.
}
Inside the loop, we need to compute the sum of the cubed digits of n. The code you wrote earlier to compute that modifies the number it's operating on, but we can't modify n, or we'll screw up the for loop. We make a copy:
for (int n = 10; n < 10000; n++) {
int temp = n;
int sum = 0;
// Compute the sum of the digits of temp, much like you did before.
}
Finally, if the sum is equal to n, we do something to indicate it. Let's say your assignment said to print all such numbers:
for (int n = 10; n < 10000; n++) {
int temp = n;
int sum = 0;
// Compute the sum of the digits of temp, much like you did before.
if (sum == n) {
System.out.println(n);
}
}
For an arbitrary integer i, it's nth digit dn is, (being n=1 the rightmost digit)
dn = (i % (10^n)) / (10^(n-1)) // all integer operations
as you can see, you'll need to know beforehand the number of digits of your i, otherwise, yes, you'll need a loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter number : ");
int num = input.nextInt();
int temp = num, remainder;
int sum = 0;
while(temp %10 != 0){
remainder = temp %10;
sum = sum+ remainder ;
temp = temp/10;
}
System.out.println("Sum of digit : " + sum);
=====OUTPUT====
Please enter number : 123
Sum of digit : 6

modulo algorithm for prime numbers

I'm trying to get a program to get me the prime numbers from a certain range (user inputs the maximum number) and this variable called maxNumber will be used to stop the while loop. The control variable used starts at the first prime number 2 and is called i and will be used to print out the prime numbers (when found) and natural numbers, respectively.
My problem is that I'm not really sure if my algorithm inside the main method and mutator method are both correct and I have a problem where I am putting the user input (the max number) but nothing is happening at all after that -- basically, it is compiling and running but not responding when inputting the first variable.
Help would very much be appreciated !
import java.util.*;
public class PrimeCalculator {
private static int maxNumber;
private static int divisibleCount;
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int i = 2;
System.out.println("Enter the maximum amount of numbers you want to find prime numbers within: ");
maxNumber = scanner.nextInt();
while(i <= maxNumber)
isPrime(i);
if(divisibleCount < 2)
System.out.println(i + " is a prime number");
if(divisibleCount > 2)
System.out.println(i + " is not a prime number.");
divisibleCount = 0;
i++;
}
public static void isPrime(int n) {
divisibleCount = 0;
for(int x = 1; x <= maxNumber; x++ )
if(n%x == 0)
divisibleCount++;
}
}
Although I do not think it is clear what you're asking, I will make a few suggestions.
First of all, at your main method, change if(divisibleCount < 2) to if(divisibleCount <= 2) because primes are divided by 1 and themselves (so, "divisibleCount" is 2).
Also, in your while loop, you should check if i equals one and say that it is not a prime.
As said in the comments, at the isPrime method , you can change the loop to for(int x = 1; x <=n; x++ ) as it is impossible for a number to be perfectly divided by soomething greater (i.e. 6 divided by 10 cannot have modulo 0)
EDIT: As dcsohl suggested, it is even better to have for(int x = 1; x <= Math.sqrt(n); x++) (see comment)
Check your syntax. At the while loop, you do not open and close brackets, so only isPrime(i) gets executed in the loop. Imagine
while(i <= maxNumber){
isPrime(i);
}
if(divisibleCount < 2) // ....etc
And since i is never incremented in the loop, it it always 2, so ... we have got an infinite loop!
(General improvement) Surround the maxNumber = scanner.nextInt(); in a try-catch block to avoid crashing when entering say, a string instead of an int.
These are the problems I found, hope I helped you.
PS. If you have any other question like this (i.e. general code checking), you should ask them at Code Review rather than Stack Overflow
I won't answer your Java questions, but the normal algorithm for enumerating the prime numbers is the Sieve of Eratosthenes, invented by a Greek mathematician over two thousand years ago:
function primes(n)
sieve := makeArray(2..n, True)
for p from 2 to n
if sieve[p]
output p # prime
for i from p*p to n step p
sieve[i] := False
This algorithm examines every number p from 2 to n; if p is prime, the loop on i marks False all the multiples of p; the i loop starts from the square of p because all smaller multiples will already have been marked False by smaller primes.
If you're interested in programming with prime numbers, I modestly recommend this essay at my blog.
import java.io.*;
class Prime
{
public static void main(String args[])
{
long i,j,n=1000000100000L;
long sum=0;
long i1=1000000000000L;
long c;
System.out.println("The Prime Numbers are:");
for(i=i1;i<=n;i++)
{
c=0;
for(j=2;j<=10000000;j++)
{
if(i%j==0)
c=c+1;
if(c==1)
break;
}
if(c==0)
{
System.out.println(i);
sum=sum+i;
}
}
System.out.println("The Sum of Prime numbers are:"+sum);
}
}

Categories

Resources