Counting the number of divisions until the sum == 0 - java

So I'm trying to divide a number by 2 repeatedly until the sum hits 0.
For example, dividing 40 by two, it will be like this 20, 10, 5, 2, 1, 0, and it will print 6, because it divided 6 times.
The code I came up with is
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter A Number:");
try {
int i = sc.nextInt();
int j = i;
int k = j/2; //sum
while (k == 0) {
System.out.println(k);
k++;
}
}
finally {
System.out.println("done");
}
}
}
I know it's very wrong, but if someone can point me into the right direction, it would be greatly appreciated!

Maybe I missed something but the solution seems quite trivial:
int i = sc.nextInt();
int count = 0;
while (i > 0)
{
i /= 2;
count++;
}
I'm not sure what "until the sum hits 0" means.

This is not kinda "algorithmic" solution but you may achieve what you need using the following approach:
public static void main(String[] args) {
System.out.println("Enter A Number:");
Scanner sc = new Scanner(System.in);
System.out.println(Integer.SIZE-Integer.numberOfLeadingZeros(sc.nextInt()));
}

Related

Lucky number with User Input

I'm facing troubles solving the following question: I suppose to get the user to input a number and check if it is a lucky number. A lucky number is the sum of squares of even-positioned digit (starting from the second position) is a multiple of 7.
Following is the example of my codes, when i run the program it will stuck at user input, please advise how do i get it to run:
public class Tester {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input a number: ");
int number = scanner.nextInt();
int count = 0;
while(number!=0) {
number/=10;
++count;
}
int[] array = new int[count];
int sum = 0;
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
for (int i=0; i<count; i++) {
if(array[i]%2==0) {
sum+=(array[i]*array[i]);
}
else {
continue;
}
}
if (sum%7==0) {
System.out.println("The number: " +number+ "is a Lucky number");
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
}
I believe the culprit is the below loop:
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
I think your intention was to get each of the digits into an array. However, you are getting an input from the scanner (which in this case is the user input) for count number of times.
While there are several ways of getting the number of digits and each digit into an array. I'm going to give you two ways. Also, I see no validations on the input integer (such as negative numbers, etc.) and I am going to ignore them right now.
Approach 1: Your for loop corrected
You just get the ith digit of the number using a formula.
for (int i=1; i<=count; i++) {
array[i] = (int) (number / Math.pow(10, count-i)) % 10;
}
Approach 2: Converting the numbers to String and back using streams
List<Integer> digits = Arrays.toStream(number.toString().split("")).map(
digitChar -> Integer.parseInt(digitChar)
).collect(Collectors.toList());
Note:
You need to import the classes java.util.Arrays and java.util.stream.Collectors
If you want even positioned digits,then you can directly get it in while loop.
while(number!=0) {
if(count%2 !=0){
int value = number %10; // even positioned values
// Do whatever you need to do with this value
}
number/=10;
++count;
}
If you want to convert the number into an digit array,then first find number of digits using log function and then store it array in reverse order.
int noOfDigits =(int) Math.floor(Math.log10(number)+1); // Finding No of digits
int[] array = new int[noOfDigits];
while(--noOfDigits>=0){
array[noOfDigits] = number/10; // storing every digits in reverse order
number%=10;
}
I don't know below code will be helpful for your core logic,yet I record this too.
If you want Sum of Squares of even positioned digits in number which is represented as array, then you can use below code.
int sum = 0;
for (int i=1; i<array.length; i+=2) {
sum += array[i] * array[i];
}
if (sum%7==0) {
// print number is lucky
}
else {
// print number is not lucky
}
If I understand your description correctly, here's a program that does what you want:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input a number: ");
System.out.flush();
int number = scanner.nextInt();
int count = 0;
int n = number;
int sum = 0;
while(n!=0) {
int d = n % 10;
n/=10;
++count;
if (count % 2 == 0) {
System.out.printf("sum = %d + %d^2 = %d\n", sum, d, sum + d * d);
sum += d * d;
}
}
if (sum%7==0) {
System.out.printf("The number: %d is a Lucky number (%d = 7 * %d)", number, sum, sum / 7);
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
A lucky result:
Input a number: 123456
sum = 0 + 5^2 = 25
sum = 25 + 3^2 = 34
sum = 34 + 1^2 = 35
The number: 123456 is a Lucky number (35 = 7 * 5)

Making a program that prints from x to y numbers depending on what the user asks

I'm new to Java sorry, I have to make this program in which it will ask the user two numbers, from those two numbers take the intervals that can be divided by 3 and then make an average of them.
I'm only focusing on making it print all the numbers since I'm trying to go step by step.
I have tried two things
On this first code it asks for both numbers but doesn't print anything
Scanner scanner = new Scanner (System.in);
double b = scanner.nextDouble();
for ( double a = scanner.nextDouble() ; a <= b; a++)
{
System.out.println(a);
}
On this second code it asks for 3 inputs and it prints the loop normally if the last input is equal to the first, I think I can see why this is happening but I don't know how to fix it:
Scanner scanner = new Scanner (System.in);
double a = scanner.nextDouble();
double b = scanner.nextDouble();
for ( a = scanner.nextDouble() ; a <= b; a++)
{
System.out.println(a);
}
You need to initialize the loop counter with the value of a and make the loop iterate until the value of b as shown below:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
int count = 0;
double sum = 0;
for (int i = a; i <= b; i++) {
if (i % 3 == 0) {
System.out.println(i);
sum += i;
count++;
}
}
System.out.println("Average: " + sum / count);
}
}
A sample run:
2
10
3
6
9
Average: 6.0
-OR-
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double a = scanner.nextDouble();
double b = scanner.nextDouble();
int count = 0;
double sum = 0;
for (double i = a; i <= b; i++) {
if (i % 3 == 0) {
System.out.println(i);
sum += i;
count++;
}
}
System.out.println("Average: " + sum / count);
}
}
A sample run:
2
10
3.0
6.0
9.0
Average: 6.0

If enter n is input and the output is in n digits and starting with (n-1)0 with 1 to (n-1)9's?

I have tried this program many times I didn't get the proper output till now please help me to solve this type of program.
input:n=3
output: 001 to 999
input:n=4
output:0001 to 9999
input:n=2
output:01 to 99
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
int sum=1,result=0;
while(number!=0)
{
result=result+(9*sum);
sum=sum*10;
number--;
}
System.out.println(result);
for(int i=1;i<=result;i++)
{
System.out.printf("%02d ",i);//here i manually mentioned the %02d but i want to take user input
}
}
You can use this code
int number = 3;
String mask = "%0" + (number) + "d%n";
int max = (int)Math.pow(10, number)-1;
for (int x = 1; x <= max; x++)
System.out.printf(mask, x);
thanks to #RalfRenz
Can you try below code ?
class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
String masked = "%0" + (num) + "d%n";
int max = (int)Math.pow(10, num)-1;
for (int k = 1; k <= max; k++)
System.out.printf(masked, k);
}}

CS50 Credit : cant seem to find the error,

the program always outputs "Invalid". I've checked my code multiple times but cant find the error. I'm a beginner at java, your help will be appreciated.
I've looked for all possible errors and different codes of this questions but it still doesnt work
package cs50;
import java.util.*;
public class Credit {
int arr[];
static long credit_card;
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter credit card number : ");
credit_card = sc.nextLong();
Credit obj = new Credit();
int count = (int)obj.countDigits();
obj.digitsToArray(count);
int sum = obj.sum(count);
obj.check(sum,count);
}
//count number of digits
long countDigits()
{
long n = credit_card;
int count = 0;
while(n>0)
{
n=n/10;
count++;
}
return count;
}
//store digits in an array
void digitsToArray(int count)
{
long m = credit_card;
arr = new int[count];
for (int i=count-1; i>=0; i--)
{
arr[i] = (int)m % 10;
m = m / 10;
}
}
//Calculate sum of digits
int sum(int count)
{
int sum = 0;
for (int i=count-2; i>=0; i=i-2)
{
int n = arr[i]*2;
if(n>9)
{
sum = sum + n%10 + (n/10 % 10);
}
else
sum = sum + n;
}
for (int i=count-1; i>=0; i=i-2)
{
int n = arr[i];
sum = sum + n;
}
return sum;
}
//Check credit card type
void check(int sum, int count)
{
if (sum%10 == 0)
{
if(count==15 && (arr[0]==3 && (arr[1]==4||arr[1]==7)))
{
System.out.println("AMEX");
}
else if(count==16)
{
if(arr[0]==5 && (arr[1]==1||arr[1]==2||arr[1]==3||arr[1]==4||arr[1]==5))
{
System.out.println("MasterCard");
}
else if(arr[0]==4)
{
System.out.println("Visa");
}
}
else if(count==13 && arr[0]==4)
{
System.out.println("Visa");
}
}
else
System.out.println("Invalid");
}
}
visa or mastercard number doesnt show expected outputs, always shows "Invalid".
In line with lexicore's suggestion, stepping through your code, your digitsToArray() method will need to be looked at in detail.
Providing the credit card number: 5105 1051 0510 5100
the digitsToArray() method sets the arr variable to: [5, 1, 0, 5, 1, 0, 5, 1, 0, 9, -1, -4, -9, 5, 8, 0] which doesn't seem right.
Check out the link that lexicore provided, it'll take you through why and how to use it.

Finding the minimum of all numbers that are positive in java

I'm having trouble to ignore the negative numbers in finding the minimum of given numbers. here is my code to print the minimum number taking 10 inputs from the user in java. (I'm a fresher student and new in java. if you find any mistake then please help me to figure it out)
Scanner k = new Scanner (System.in);
int x, y, min;
System.out.println ("enter a number");
x = k.nextInt();
min = x;
for (int count=1; count < 10; count++) {
System.out.println ("enter a number");
y = k.nextInt;
if (y < min) {
min = y;
}
}
System.out.println (min);
That was my code to find the minimum number. But I want to find the minimum of all positive numbers. if the user enters negative number then I want to ignore that number.
Help me to make the code of finding the minimum number ignoring negative numbers.
if(y<min&&y>=0)
Is that what you mean?
private static Scanner k = new Scanner (System.in);
public static void main(String[] args) {
int min=getNumber(false);
for (int count=1; count<10; count++) {
int y=getNumber(true);
if(y<min&&y>=0)
min=y;
}
System.out.println(min);
}
private static int getNumber(boolean allowNegative) {
System.out.println("Please enter an integer:");
int n=0;
try {
n=Integer.parseInt(k.nextLine());
} catch(NumberFormatException nfe) {
System.err.println("Input must be an integer...");
return getNumber(allowNegative);
}
if(allowNegative) {
return n;
} else {
if(n<0) {
System.out.println("You cannot start with a negative number...");
return getNumber(allowNegative);
} else {
return n;
}
}
}
Check not only if the next number is smaller than your current minimum, but also if it is greater than (or equal) 0:
if (y<min && y >= 0){
instead of
if (y<min){
You also have to make sure the first number is not negative.
It's better if you store your all input number in an int array. If I assume the array containing all number is - array[] then look the code -
public class FindMinimumExceptNegative{
public static void main(String[] args){
int[] array = {-100, -4, 33, 45, 67, 2, -4, 56, 87, 234, 98, 24, 98, 56, 87, -10};
System.out.println("Minimum :" +findMinimumExceptNegative(array));
}
public static int findMinimumExceptNegative(int[] a){
int minimum = 0;
for(int i=0; i<a.length; i++){
if(a[i]>=0){
minimum = a[i];
break;
}
}
for(int i=1; i<a.length; i++){
if(minimum > a[i] && a[i]>=0){
minimum = a[i];
}
}
return minimum;
}
}
Scanner k=new Scanner (System.in);
int x,y,min;
min=0;
for (int count=1;count<=10;count++){
System.out.println ("enter a number");
y=k.nextInt;
if (y<min && y>=0){
min=y;
}
}
System.out.println (min);
Made a few changes. This
1) Ensures only 10 inputs are taken
2) The value of min defaults to 0 if only negative numbers are entered. In your earlier code, if the first number was negative, min would still be set.

Categories

Resources