I am trying to print each digit of an integer and then sum of each digit like this. There is something wrong with the loops but I cant seem to figure it out. I want it to be like this:
Please enter a number: 194
1 * 100 = 100
9 * 10 = 90
4 * 1 = 4
import java.util.Scanner;
public class PrintEachDigits {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = scan.nextInt();
String s = ""+num;
double d = 0;
for(int i = 0; i < s.length(); i++) {
for(int j = s.length()-1; j >= 0; j--) {
d = Math.pow(10,j);
System.out.println(s.charAt(i) + " * " + d
+ " = " + (s.charAt(i)*d));
}
}
}
}
This is the output of my code:
Enter the number: 194
1 * 100.0 = 4900.0
1 * 10.0 = 490.0
1 * 1.0 = 49.0
9 * 100.0 = 5700.0
9 * 10.0 = 570.0
9 * 1.0 = 57.0
4 * 100.0 = 5200.0
4 * 10.0 = 520.0
4 * 1.0 = 52.0
There's a couple problems with your code.
The first problem is that you don't need two loops, you just need one.
The second problem is confusing chars and ints. '0' is not the same as 0; instead, '0' is a numeric value representing the encoding of that character (which turns out to be 48). So to get the correct value that you want, you should subtract '0' from the char before doing your math.
for(int i = 0; i < s.length(); i++) {
d = Math.pow(10, s.length() - i - 1);
int value = s.charAt(i) - '0';
System.out.println(value + " * " + d
+ " = " + (value*d));
}
This will get it close to the output you wanted. It's still showing the .0 at the end though, because d is a double. Make it an int to fix that.
//This can be scoped to inside the loop, so you don't need to declare it beforehand
int d = (int)Math.pow(10,j);
import java.util.Scanner;
public class PrintEachDigits {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = scan.nextInt();
String s = "" + num;
int len = s.length() - 1;
long d = 0;
if (len < 2) {
d = 1;//For single digit
} else {
d = (long)Math.pow(10, len);
}
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i) + " * " + d + " = "
+ ((s.charAt(i) - '0') * d));
d = d / 10;
}
}
}
Related
So I want to create a timetable in java from n1 to n4, so two numbers are inputted in the scanner.
For example
Sample input:
5
7
And then the output should be the timetables from 5 to n4 until 7
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
6 * 1 = 6
6 * 2 = 12
6 * 3 = 18
6 * 4 = 24
7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
See how the middle number is only till 4 and outputs timetable from the first to the last number
This has to be done with nested for loops only with only one print statement
This is what I tried but my output was:
My output:
It displays the results up to 4 but for each one, it does it 8 times, and
only for 5
My code:
import java.util.Scanner;
public class Timestables {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int n1 = keyboard.nextInt();
int n2 = keyboard.nextInt();
for (int y = 1; y <= 4; y++) {
for (int x = n1; x <= n2; x++) {
int result = n1 * y;
System.out.println(n1 + "*" + y + "=" + result);
}
}
}
}
The variable n1 represents the first number, and n2 represents the last number
Another way to achieve this
import java.util.Scanner;
public class A {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int number1 = keyboard.nextInt();
int number2 = keyboard.nextInt();
do {
int count = 1;
while (count <= 4) {
System.out.println(number1 + " * " + count + " = " + number1 * count++);
}
number1++;
} while (number1 <= number2);
}
}
The bounds of the outer loop should be from n1 to n2, inclusive on both ends. The bounds of the inner loop should be from 1 to 4:
Scanner keyboard = new Scanner(System.in);
int n1 = keyboard.nextInt();
int n2 = keyboard.nextInt();
for (int i=n1; i <= n2; ++i) {
for (int j=1; j <= 4; ++j) {
int result = i*j;
System.out.println(i + " * " + j + " = " + result);
}
}
}
This prints, using inputs of n1=5 and n2=7:
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
6 * 1 = 6
6 * 2 = 12
6 * 3 = 18
6 * 4 = 24
7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
You can do this :
import java.util.Scanner;
public class Timestables {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int n1 = keyboard.nextInt();
int n2 = keyboard.nextInt();
for (int i = n1; i <= n2; i++) { // from n1 = 5 to n2 = 7
for (int j = 1; j <= 4; j++) { // multiplication from 1 to 4
System.out.println(i + "*" + j + "=" + i * j);
}
}
}
}
I am new to Java and stackoverflow. I am writing a program that can add power in Java, for example: 2^1, 2^1+2^2, 2^1+2^2+2^3,.. so on.
I have written below program and I don't know what I am doing wrong when I am trying to add the powers. I just get 2^1 2^2 2^3,... as output. I hope you get the idea from my code and it will be a great help if you guys can help me learn.
Thank you in advance!
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter b: ");
int b = sc.nextInt(); //b = second number
System.out.print("Enter t: ");
int t = sc.nextInt(); //t = no. of iterations
int x=0, sum = 0;
for (int i = 0; i < t;) {
for (int j = 0; j < t; j++) {
int pow = (int) Math.pow(2, i);
x = a + (pow * b);
i++;
System.out.printf("%d ", x);
sum = x;
}
sum = x + sum;
System.out.println(sum);
}
}
According to Mathematics rules, if it is addition among the numbers, for example 2^1 + 2^2 + 2^3 + 2^4... Then it is simple you don't need two loops and the t variable. You just need the base and the last exponent limit.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the base: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter iterations: ");
int b = sc.nextInt(); //b = No of iterations
int sum = 0;
for (int i = 1; i <= b; i++) {
sum += Math.pow(a, i);
}
System.out.println("The sum is " + sum);
}
But if there is multiplication among the numbers, then you will add the exponents if the base is same. Fox example 2^1 * 2^2 * 2^3 * 2^4.... Then you may do it as below.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the base: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter iterations: ");
int b = sc.nextInt(); //b = No of iterations
Double res;
int powerSum = 0;
for (int i = 1; i <= b; i++) {
powerSum += i;
}
System.out.println("Power sum is " + powerSum);
res = Math.pow(a, powerSum);
System.out.println("The result is " + res);
}
In your inner loop
int pow = (int) Math.pow(2, i);
shouldn't you be using j instead of i?
Very simply you can do it as below:
public static int getPow(int num, int pow) {
if (pow < 2) {
return num;
}
return (int) Math.pow(num, pow) + getPow(num, --pow);
}
Usage:
int pow = getPow(2, 4);// 2*1 + 2*2 + 2*2*2 + 2*2*2*2 = 2+4+8+16 = 30
System.out.println("pow = " + pow);
And Result:
pow = 30
I am working on an interview question which I was asked in which I was supposed to write a program to find the largest palindrome from product of two three digit numbers.
Here is the question
I came up with this brute force approach which starts from bottom.
public class LargestPalindromeQuestion {
public static void main(String[] args) {
int value = 0;
for (int i = 100; i <= 999; i++) {
for (int j = i; j <= 999; j++) {
int value1 = i * j;
if (isPalindrome(value1) && value < value1) {
value = value1;
}
}
}
System.out.println(value);
}
private static boolean isPalindrome(final int product) {
int p = product;
int reverse = 0;
while (p != 0) {
reverse *= 10;
reverse += p % 10;
p /= 10;
}
return reverse == product;
}
}
They asked me what are the optimizations I can do in this program? I mentioned that we can try pruning the search space and optimize checking step for each item in the search space but then I am confuse how would I make this work in my above solution?
What are the optimizations we can do in this program? Right now it is executing 810000 steps to find the largest palindrome.
What is the least number of steps we can execute to find the largest palindrome in two three digit numbers?
The program looks very good to me. I would make the i loop count from 999 down to 100, and I would only check j values that would actually give a larger product than the current maximum.
This program is able to finish surprisingly soon, at i == 952 to be precise. The mathematical reason for this is that once the solution 906609 (993 * 913) is found, it will no longer be possible to find a larger palindrome where the larger factor is less than the square-root of 906609, which is 952.160....
public static void main(String[] args) {
int value = 0;
for (int i = 999; i >= 100; i--) {
int r = value / i;
if (r >= i) {
System.out.println("We broke at i = " + i);
break;
}
for (int j = i; j > r; j--) {
int value1 = i * j;
if (isPalindrome(value1)) {
value = value1;
break;
}
}
}
System.out.println(value);
}
One pretty simple way of optimizing this would be to simply start with the highest 3-digit numbers instead of the smallest. Since the solution will most likely be closer to the pair (999 , 999) than to (100 , 100).
One useful mechanism to prune the search tree is to notice that the highest digit of the product a * b doesn't change often. E.g.
a = 111; b = 112 a*b = 12432
; b = 113 a*b = 12543
; b = 114 a*b = 12654
; ...
; b = 180 a*b = 19980
; b = 181 a*b = 20091 = (19980 + a)
Thus, for all the values in between (a = 111, a < b < 181), one already knows the MSB, which must equal to the LSB or (a % 10) * (b % 10) % 10 == MSB.
e.g.
LSB = 1 --> a % 10 == 1, b % 10 == 1
OR a % 10 == 3, b % 10 == 7
OR a % 10 == 7, b % 10 == 3
OR a % 10 == 9, b % 10 == 9
Most of the time there's either none, or just one candidate in set 'b' to be checked for any pair MSB, a % 10.
The least number of steps I could get to is 375. Consider multiplying the three-digit number, a1a2a3, by the three-digit number, b1b2b3:
JavaScript code:
var modHash = new Array(10);
var iterations = 0;
for (var i=1; i<10; i++){
modHash[i] = {0: [0]}
for (var j=1; j<10; j++){
iterations ++;
var r = i * j % 10;
if (modHash[i][r])
modHash[i][r].push(j);
else
modHash[i][r] = [j];
}
}
var highest = 0;
function multiples(x,y,carry,mod){
for (var i in modHash[x]){
var m = (10 + mod - i - carry) % 10;
if (modHash[y][m]){
for (var j in modHash[x][i]){
for (var k in modHash[y][m]){
iterations ++;
var palindrome = num(9,modHash[y][m][k],x,9,modHash[x][i][k],y);
if (x == 3 && mod == 0){
console.log(x + " * " + modHash[x][i][j] + " + "
+ y + " * " + modHash[y][m][k] + ": " + palindrome);
}
var str = String(palindrome);
if (str == str.split("").reverse().join("") && palindrome > highest){
highest = palindrome;
}
}
}
}
}
}
function num(a1,a2,a3,b1,b2,b3){
return (100*a1 + 10*a2 + a3)
* (100*b1 + 10*b2 + b3);
}
var a3b3s = [[7,7,4],[9,1,0],[3,3,0]];
for (var i in a3b3s){
for (var mod=0; mod<10; mod++){
var x = a3b3s[i][0],
y = a3b3s[i][1],
carry = a3b3s[i][2];
multiples(x,y,carry,mod);
}
}
console.log(highest);
console.log("iterations: " + iterations);
Output:
3 * 0 + 3 * 0: 815409
3 * 7 + 3 * 3: 907809
3 * 4 + 3 * 6: 908109
3 * 1 + 3 * 9: 906609
3 * 8 + 3 * 2: 907309
3 * 5 + 3 * 5: 908209
3 * 2 + 3 * 8: 907309
3 * 9 + 3 * 1: 906609
3 * 6 + 3 * 4: 908109
3 * 3 + 3 * 7: 907809
906609
iterations: 375
First optimize isPalindrome by seperating 6 digits as 3 digits. i.e. N = ABCDEF => a = ABC = N/1000, b = DEF = N%1000; Then reverse b and return a==reversed_b;
Secondly while producing palindromes loop through till max_palindrome_so_far/999 which is the minimum value that you would use. max_palindrome_so_far is initially equals N.
public class Solution {
public static boolean isPalindrome(int n){
int a = n/1000;
int b = n%1000;
int d, r = 0, i = 3;
while(i-- > 0){
d = b%10;
r = r*10 + d;
b = b/10;
}
if (a == r)
return true;
return false;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
int n = in.nextInt();
int r=0, m=n;
int i,j;
for(i = 999;i>=100;i--){
for(j = 999;j>=m/999;j--){
if (i*j < n && i*j > 100000 && isPalindrome(i*j)){
r = Math.max(i*j, r);
m = r;
}
}
}
// System.out.println(i + " * " + j + " = " + i*j);
System.out.println(r);
}
}
}
I managed to get the result if I enter the base and exponent, but the output should be
For example: the output should look like this
>>base:5 exponent: 2
5^2 = 25
5^1 = 5
I need help to put something somewhere to make this happen...
import java.util.Scanner;
public class recursion {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int base = 0;
int expo = 0;
System.out.print("Enter number for base ");
for (int i = 0; i < 1; i++)
base = scanner.nextInt();
System.out.print("Enter number for exponent ");
for (int j = 0; j < 1; j++)
expo = scanner.nextInt();
System.out.println(base + "^" +expo +" = " + pow(base,expo));
}
public static int pow(int x, int p) {
System.out.println(x + "^" +p +" = " );
if (p == 0)
return 1;
if (p % 2 == 0) {
int a = pow(x, (p / 2));
return a * a; // This line
} else {
int a = pow(x, ((p - 1) / 2));
return x * a * a; // This line
}
}
}
Firstly, the following code snippets demands a review:
{
for (int i = 0; i < 1; i++)
/*
* This for loop is unnecessary.
* It asserts that the following clause is run only once,
* which is true for any statements anyway.
*/
// ...
}
return a * a;
} /* if (p % 2 == 0) */ else {
/*
* Statements are unnecessarily nested within else clause.
* The corresponding then clause does not complete normally.
* Moving the following code snippet out of an else block
* would have the same effect, but simplifies the control
* statements.
*/
int a = pow(x, ((p - 1) / 2));
return x * a * a;
}
Within your pow() method, you have a System.out.println() method. You're calling it for debugging, but it's unnecessary as the process returns normally. As you're looking for printing the operations for exponent as "from user-specified exponent -> 1" ("in descending order"), use a loop to print your System.out.println(base + "^" + expo + " = " + TestClass.pow(base, expo));:
do // New!
System.out.println(base + "^" + expo + " = " + TestClass.pow(base, expo));
while (expo-- > 1); // New!
} /* main( args ) */
and you can remove the debugging line in pow().
Example: (>> denotes STDIN)
Enter number for base >> 5
Enter number for exponent >> 2
5^2 = 25
5^1 = 5
Enter number for base >> 4
Enter number for exponent >> 5
4^5 = 1024
4^4 = 256
4^3 = 64
4^2 = 16
4^1 = 4
View a live code demo.
void power(int base, int exp){
//Use for loop to iterate through each exp down to 0
for(int i=exp; i>=0; i--){
int result= exponent(base,i);
System.out.println(base + "^" + i + "=" + result)//Will display result as 5^2=25
}
//Recursively computes the result of b^e.
int exponent(int b, int e){
if(e==0){//Base case occurs when e=0.
return (1);
}
return (b * exponent(b,e-1));
}
import java.io.*;
public class TestCaseAbcd {
public static void main(String args[]) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(
float x0;
float a, c, mod;
int num, ch = 0;
double[] rNumbers;
double[] rTemp;
System.out.println("Enter the SEED value: ");
System.out.println("x0 ");
x0 = Float.parseFloat(stdin.readLine());
System.out.println("Enter the multiplier's value:");
System.out.println("a: ");
a = Float.parseFloat(stdin.readLine());
System.out.println("Enter the value of increment c and modulus m: ");
System.out.println("c: ");
c = Float.parseFloat(stdin.readLine());
System.out.println("m: ");
mod = Integer.parseInt(stdin.readLine());
System.out.println("How many random nunbers u need? ");
num = Integer.parseInt(stdin.readLine());
rNUmbers = new double[num];
rTemp = new double[rNumbers.length];
rTemp[0] = x0;
for (int i = 0; i < num; i++)
{
if(i + 1 != num)
{
rTemp[i + 1] = (((rTemp[i] * a) + c) % mod);
}
else
{
break;
}
}
for (int i = 0; i < rNumbers.length; i++)
{
if (i + 1 != num)
{
rNumbers[i] = rTemp[i] / mod;
}
else
{
break;
}
}
System.out.println("The PSEUDO random numbers are: ");
for (int i = 0; i < rNumbers.length; i++)
{
System.out.println(rNumbers[i]);
}
double firstNum = rNumbers[0];
System.out.println("1. Select Mutant 1 ");
System.out.println("2. Select Mutant 2 ");
System.out.println("3. Exit ");
}
}
In the above code, the expected output should start from: 0.68.
But, instead it started from:
0.37.
In fact, even after I changed the following code:
rTemp[i+1] = ( ( (rTemp[i]*a) + c ) % mod);
to:
rTemp[i+1] = ( ( (rTemp[i]/a) + c ) % mod);
The output still started from 0.37.
The input values are:
x0 = 37
a = 7
c = 9
m = 100
Please help me in analyzing the code so as that the output shouldn't start with 0.37.
Summary of the problem: the code is producing the same number i.e. 0.37 no matter what the equation stated above in the code is modified to.
You're setting the first value in rTemp to 37, then you start printing from the first value. It only makes sense that the first value printed would be 0.37.
x0 = 37
mod = 100
...
rTemp[0] = x0;
...
rNumbers[i] = rTemp[i] / mod;
...
System.out.println(rNumbers[i]);
To achieve the output you're looking for, change this:
rTemp[0] = x0;
for (int i = 0; i < num; i++)
{
if(i + 1 != num)
{
rTemp[i + 1] = (((rTemp[i] * a) + c) % mod);
}
else
{
break;
}
}
to this:
rTemp[0] = (((x0 * a) + c) % mod);
for (int i = 0; i < num-1; i++)
{
rTemp[i + 1] = (((rTemp[i] * a) + c) % mod);
}
On a side note, if all you really want is an array of psudo-random doubles, it's easier to do something like this:
Random rnd = new Random(seed);
double[] rNumbers = new double[num];
for(int i = 0; i < num; i++)
rNumbers[i] = (double)rnd.nextInt(100) / 100;
For any given seed, you'll get the same array of doubles every time.