Product of digits - java

public class ProductOfDigits {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = input.nextInt();
int x = Math.abs(n);
int product = 1;
if (x >=0 && x<=9) {
System.out.println(x);
}
else {
product = product * (x % 10);
x = x/10;
System.out.println(product);
}
When the input is negative number, the product is between first and last digit. Can anyone explain? I have tried Math.abs() to get absolute value but it is impossible and it is killing me now.

Do it as follows:
import java.util.Scanner;
public class ProductOfDigits {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = input.nextInt();
int x = Math.abs(n);
int ç = 1;
int product = 1;
if (x == 0) {
product = 0;
} else {
while (x > 0) {
product *= x % 10;
x /= 10;
}
}
System.out.println(product);
}
}
Sample run-1:
Enter an integer: -256
60
Sample run-2:
Enter an integer: 0
0
Sample run-3:
Enter an integer: 9
9
Sample run-4:
Enter an integer: 256
60
Recursive version:
import java.util.Scanner;
public class ProductOfDigits {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = input.nextInt();
System.out.println(productOfDigits(n));
}
static int productOfDigits(int n) {
n = Math.abs(n);
if (n > 0 && n < 10) {
return n;
}
if (n == 0) {
return 0;
}
return (n % 10) * productOfDigits(n / 10);
}
}

You can use Math.log10() function from java to get the number of your digits and then calculate the first digit based on it:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
if (number < 0) {
number *= (-1);
}
int digits = (int) Math.log10(number);
int lastDigit = number % 10;
int firstDigit = (int) (number / Math.pow(10, digits));
int product = lastDigit * firstDigit;
System.out.println(product);
}
And of course, if your number is negative, you can use Math.abs() (instead of if)

Your current code only prints out the last digit of the entered integer because you are only doing product = product * (x % 10); (can be simplified to product *= x % 10;) and x = x / 10; (can be simplified to x /= 10;) once each. You should repeatedly do these two operations until x is 0.
You could use a for loop or a while loop for this. Here's how to write this with a for loop:
for (; x > 0 ; x /= 10) {
product *= x % 10;
}
The condition for the if statement can also be changed to just x == 0, as the x values 1-9 can all be correctly handled by the else clause.

Related

"if" condition problem in java Armstrong code

I wrote the armstrong number question in java by myself(sorry if its silly, I'm new to programming).
The "result is supposed to give 1 value when i enter a coorect armstrong number but it gives 0,why?
Code-
import java.util.Scanner;
public class Exercise1_4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int result = 0;
int i = 0;
int sum = 0;
while (n > 0) {
i = n % 10;
sum += i * i * i;
n = n / 10;
}
if (sum == n) {
System.out.print("1");
} else {
System.out.print("0");
}
n is changed in the while loop. After the while loop n == 0 (if n was entered as a non-negative number). This the only case where sum == n is true will be sum == 0. You need to introduce a temporary variable which is modified in the loop and keep n unchanged.
int temp = n;
while (temp > 0) {
int i = temp % 10;
sum += i * i * i;
temp /= 10;
}
N.B. result is not used, i not decalred inside the while loop

convert decimal to binary

Code is mostly done but my code is printing incorrectly its printing out as 110 as opposed to 011. The problem im doing requires to reverse the "110" to "011"
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num, binaryNum = 0;
int i = 1, rem;
num = scan.nextInt();
while (num != 0)
{
rem = num % 2;
num /= 2;
binaryNum += rem * i;
i *= 10;
}
System.out.println(binaryNum);
}
}
Then use a string as follows:
int num = scan.nextInt();
String s = "";
while (num != 0) {
int rem = num % 2;
num /= 2;
s = s + rem; // this concatenates the digit to the string in reverse order.
// if you want it in normal order, do it -> s = rem + s;
}
System.out.println(s);
You may directly print each binary digit without storing it in binaryNum
while (num != 0) {
System.out.print(num % 2);
num /= 2;
}
System.out.println();
You can simply use Integer#toBinaryString(int) to return the result as a binary string.
Scanner scan = new Scanner(System.in);
int value = scan.nextInt();
System.out.println(Integer.toBinaryString(value));

Three consecutive numbers in a while loop

Write a program that reads integers from the user until he enters -1, and print “Consecutive ” if there are three consecutive numbers otherwise print “None Consecutive”; that is in the number list you read are in an order such that there is some integer k that the numbers values are k, k+1, and k+2.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = x + 1;
int z = x + 2;
boolean areConsecutive = false;
while (x != -1) {
if (x == y) {
x = scan.nextInt();
if (x == z)
areConsecutive = true;
}
x = scan.nextInt();
}
if (areConsecutive)
System.out.print("Consecutive");
else
System.out.print("None Consecutive");
}
Can anyone please tell me what's wrong with this code?
Get the next integer before checking with y, then check for z. if one of these fails update y and z and check again.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = x + 1;
int z = x + 2;
boolean areConsecutive = false;
while (x != -1) {
x = scan.nextInt();
if (x == y) {
x = scan.nextInt();
if (x == z)
areConsecutive = true;
}
y = x + 1;
z = x + 2;
}
if (areConsecutive)
System.out.print("Consecutive");
else
System.out.print("None Consecutive");
}
You need to increment y and z by 1 before scaning new x.
This is what you are looking for:
Scanner scan = new Scanner(System.in);
System.out.println("enter");
int x = scan.nextInt();
boolean areConsecutive = false;
while (x != -1) {
int y = x + 1;
System.out.println("enter");
x = scan.nextInt();
if (x == y) {
System.out.println("enter");
int z = x + 1;
x = scan.nextInt();
if (x == z)
areConsecutive = true;
}
}
if (areConsecutive)
System.out.println("Consecutive");
else
System.out.println("None Consecutive");
You're close but you're not maintaining the history of the numbers correctly.
First, to clarify, the specification calls for you to enter an arbitrary quantity of arbitrary numbers from the user and simply check if any three of them are consecutive. Hence the first line below would have a consecutive sequence (the 1 2 3 bit starting at the third number) but the second would not:
9 9 1 2 3 9
3 1 4 1 5 9
One way to do this is simply maintain the minimal information to detect a consecutive sequence. To do that, you need to keep a copy of only the last three numbers entered. The pseudo-code (easily transformable into any procedural language) for such a beast would be:
# Get first number, ensure no chance of consecutive
# sequence until at least three are entered.
num3 = getint()
num2 = num3
num1 = num3
consecutive = false
# Loop until -1 entered.
while num3 != -1:
# Check for consecutive sequence.
if (num1 + 1 == num2) and (num2 + 1 == num3):
consecutive = true
# Shift numbers "left".
num1 = num2
num2 = num3
num3 = getint()
if consecutive:
print "Consecutive"
else
print "None Consecutive"
This is what you are looking for:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
int z = scan.nextInt();
boolean areConsecutive = false;
while ((x != -1)&&(y != -1)&&(z != -1)){
if ((z == y + 1)&&(y == x + 1)
areConsecutive = true;
if (areConsecutive)
System.out.print("Consecutive");
else
System.out.print("None Consecutive");
}
I would do it this way, we have to check if three numbers are consecutive no matter the order they were entered by user:
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int[] numbers = new int[3];
for( int i = 0; i < numbers.length; ++i)
numbers[i] = scan.nextInt();
Arrays.sort(numbers);
boolean areConsecutive = true;
for( int i = 0; i < numbers.length - 1; ++i)
if(numbers[i+1] - numbers[i] != 1)
areConsecutive = false;
if(areConsecutive)
System.out.print("Consecutive");
else
System.out.print("None Consecutive");
}

Not printing perfect numbers

Here is my code :-
package javaapplication;
import java.util.Scanner;
public class perfect02 {
public static void main(String args[]) {
int i = 1, sum = 0;
System.out.println("Enter maximum range : ");
Scanner kb = new Scanner(System.in);
int a = kb.nextInt();
System.out.println("Enter minimum range : ");
Scanner kb2 = new Scanner(System.in);
int b = kb2.nextInt();
System.out.println("perfect number in the given range are :");
for (int n = b; n <= a; n++) {
while (i < n) {
if (n % i == 0) {
sum = sum + i;
}
i++;
}
if (sum == n)
System.out.println(+n + " ");
}
}
}
Why program is not printing perfect numbers ?
I have checked code many times but i am unable to find the solution .Please tell me what is going wrong in my code .Thanks in advance
Any help would be appreciated ....
Here, I looked into the perfect number generation and fixed it for you!
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter minimum range : ");
int b = kb.nextInt();
System.out.println("Enter maximum range : ");
int a = kb.nextInt();
kb.close();
System.out.println("Perfect number in the given range are :");
for (int n = b; n <= a; n++) {
int sum = 0;
int i = 1;
while (i < n) {
if (n % i == 0)
sum = sum + i;
i++;
}
if (sum == n)
System.out.println(n + " is perfect");
}
}
You should've had the sum and i variables declared inside the for loop, so they would be reset for each number!

Armstrong number checking in Java

I'm trying to write a class which checks if a number is an Armstrong number or not. I'm having trouble with the following block of code.
public boolean checkNum(long num) {
digits = (int) (Math.log10(num) + 1);
String number = String.valueOf(num);
numDigits = number.toCharArray();
for (int i = 0; i < numDigits.length; i++) {
digit = numDigits[i] * 1.0;
power = digits * 1.0;
sum = sum + (long) (Math.pow(digit, power));
}
if (sum == num) {
return true;
} else {
return false;
}
}
The casting doesn't seem to work, and checkNum returns false every time. Is this a correct method, and are there any better ways of doing this?
Try this, using only arithmetic operations and it works for non-negative integers with an arbitrary number of digits (as long as they fit into a long).
public boolean checkNum(long num) {
long n = num;
long sum = 0;
// find the number of digits
int power = (int) Math.floor(Math.log10(n == 0 ? 1 : n)) + 1;
while (n != 0) {
int digit = (int) n % 10;
sum += Math.pow(digit, power);
n /= 10;
}
return sum == num;
}
Alternatively (albeit less efficiently) you could transform the number into a string and iterate over each of the characters converting them into digits. Here's a fixed version of your intended solution, with comments on the key points:
public boolean checkNum(long num) {
String number = String.valueOf(num);
char[] numDigits = number.toCharArray();
long sum = 0;
// a simple way to obtain the number of digits
int power = numDigits.length;
for (int i = 0; i < numDigits.length; i++) {
// this is how we transform a character into a digit
int digit = Character.digit(numDigits[i], 10);
// we need to rise digit to the value of power
sum = sum + (long) Math.pow(digit, power);
}
if (sum == num) {
return true;
} else {
return false;
}
}
For example, use either implementation to verify that the following are Armstrong numbers:
checkNum(6)
=> true
checkNum(371)
=> true
checkNum(1634)
=> true
You can also use this simple logic
public class Armstrong {
public static void main(String[] args) {
int number = 371, originalNumber, remainder, result = 0;
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber % 10;
result += Math.pow(remainder, 3);
originalNumber /= 10;
}
if(result == number)
System.out.println(number + " is an Armstrong number.");
else
System.out.println(number + " is not an Armstrong number.");
}
}
Guess This will work:
boolean isArmstrong(int x){
int s=0;
int u=x;
while(x!=0)
{
int y=x%10;
s=s+(y*y*y);
x=x/10;
}
if(u==s)
return true;
else
return false;
}
How to Check Number is Armstrong or Not
public boolean isArmstrongNum(int input)
{
int sum=0,rem,temp;
temp=input;
while(input>0)
{
rem=input%10;
input=input/10;
sum=sum+(rem*rem*rem);
}
return sum==temp;
}
In Kotlin, you can use:
fun main() {
println("---------------------------------------")
val userInputValues = Scanner(System.`in`)
//* Kotlin Program to Display Armstrong Numbers Between Intervals Using Function
println("* Kotlin Program to Display Armstrong Numbers Between Intervals Using Function\n")
println("Enter your number range")
println("Enter start number of your range \t ")
val startRange = userInputValues.nextInt()
println("Enter end number of your range \t ")
val endRange = userInputValues.nextInt()
println("\n\n------ Armstrong number between $startRange and $endRange ------ ")
for (number in startRange..endRange) {
var stringNumber : String = number.toString()
var numberArray = stringNumber.toCharArray()
var powerOfNumber:Int = numberArray.size;
var result = 0
for (digit in numberArray){
var intDigit:Int = digit.toString().toInt()
result += intDigit.toDouble().pow(powerOfNumber.toDouble()).toInt()
}
if(result == number){
println( "$number is Armstrong number")
}
}
println("---------------------------------------")
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter the number: ");
int number=scanner.nextInt();
scanner.close();
int lastDigit=0;
int reverseNum=0;
int originalNumber=number;
while(originalNumber!=0) {
lastDigit=originalNumber%10;
reverseNum +=(lastDigit*lastDigit*lastDigit);
originalNumber /=10;
}
if(reverseNum==number) {
System.out.println("Number is Armstrong");
}
else {
System.out.println("Number is not Armstrong");
}
}
This image is testing image of this code in terminal.
The best way is using while loop.
Here is your Answer for finding 3 digits Armstrong numbers.
import java.util.Scanner;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[])
{
System.out.println("Hello world!");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int numc = num;
int rem = 0;
int cu = 0;
int val = 0;
while(num != 0){
rem = num%10;
cu = rem*rem*rem;
val += cu;
num /= 10;
}
if(val == numc){
System.out.println("Yes its a Armstrong number ");
}else{
System.out.println("No its not a Armstrong number ");
}
}
}
///////////////////////////////////////////
Here I have done a code to find armstrong number dynamically:
import java.util.Scanner;
public class Armstrong {
public static void main(String[] args) {
if(isArmstrongNumber(input())) {
System.out.println("armstrong number");
} else {
System.out.println("Not armstrong number");
}
}
private static int input() {
try(Scanner reader = new Scanner(System.in)) {
return reader.nextInt();
}
}
private static int digitCount(int num) {
int count = 0;
while(num > 0) {
num = num / 10;
count++;
}
System.out.println("No of digit : " + count);
return count;
}
private static int power(int num, int count) {
int sum = 0;
while(num > 0) {
int result = 1;
int r2 = num % 10;
num /= 10;
for(int digit = count; digit > 0; digit--) {
result *= r2;
}
sum += result;
}
System.out.println("Sum : " + sum);
return sum;
}
public static boolean isArmstrongNumber(int num) {
int count = digitCount(num);
int sum = power(num, count);
return sum == num;
}
}
Here is the result:
371
No of digit : 3
Sum : 371
armstrong number
Hope this code helps you better.

Categories

Resources