I know I could generate it using Math.log(2) but I when I try to make up my own program to generate a natural log of 2 it continuously print 1. This is my code:
import java.math.BigDecimal;
import java.util.Scanner;
public class Ques11 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
BigDecimal sum = new BigDecimal(1);
for(int i = 2; i <= n; i++) {
sum.add(new BigDecimal(1/n));
}
System.out.print(sum.setScale(10).toPlainString());
}
}
I have tried to use float, double and int and in the end used BigDecimal but I still got 1 as the result I don't know why.
P.S It actually throws InputMismatchException when big numbers are given i.e greater than 2000000000 or 2 Billion.
n is defined as an int and 1 is an int literal. When you divide two ints you use integer arithmetic, which would return only the whole part of the fraction - in your case, 0.
To rectify this, you should use doubles:
public class Ques11 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double d = scan.nextInt(); // Note we're assigning to a double
BigDecimal sum = new BigDecimal(1);
for(int i = 2; i <= d; i++) {
sum.add(new BigDecimal(1.0/d));
}
System.out.print(sum.setScale(10).toPlainString());
}
}
Related
I tried to create a code to take in a whole number in Java and output it in binary. The problem would seem that the binary is printing out backward. For instance, 6 should output as 011 but comes out as 110.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
int userNum;
Scanner in =new Scanner(System. in );
userNum = in.nextInt();
binary(userNum);
System.out.print("\n");
}
private static void binary(int userNum) {
int remainder;
while (userNum <= 1) {
System.out.print(userNum);
return;
}
remainder = userNum % 2;
binary(userNum >> 1);
System.out.print(remainder);
}
}
I tried incorporating a push stack to push the remainder into a stack that I can pull later, but couldn't quite get it to land.
private static void reverse(int userNum) {
String backwards;
while (userNum >= 0) {
backwards.push(int userNum);
System.out.println(backwards);
return;
}
}
It is part of a class assignment which asks the following.
Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary. For an integer x, the algorithm is:
As long as x is greater than 0
Output x % 2 (remainder is either 0 or 1)
x = x / 2
Note: The above algorithm outputs the 0's and 1's in reverse order.
Ex: If the input is:
6
the output is:
011
6 in binary is 110; the algorithm outputs the bits in reverse.
These are the tests the program applies and my results.
Input 6
Your output binary is:110
Expected output 011
Input 19
Your output 10011
Expected output 11001
Input 255
Your output 11111111
Expected output 11111111
Any help or guidance in this, I would be greatly appreciative of it.
Per the requirement and not taking into consideration of negative numbers
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
int userNum;
Scanner scnr = new Scanner(System.in);
userNum = scnr.nextInt();
while(userNum > 0){
System.out.print(userNum % 2);
userNum = userNum / 2;
}
System.out.print("\n");
}
}
First using predefined method then a custom one.
public class IntToBinary {
public static void main(String[] args) {
int decimalNumber = 10;
System.out.println(Integer.toBinaryString(decimalNumber));
System.out.println(convertBinary(10));
}
public static String convertBinary(int num) {
StringBuilder sb = new StringBuilder();
int binary[] = new int[40];
int index = 0;
while (num > 0) {
binary[index++] = num % 2;
num = num / 2;
}
for (int i = index - 1; i >= 0; i--) {
sb.append(binary[i]);
}
return sb.toString();
}
}
Your program appears to work fine for positive values. However it does not handle negative numbers which have their own unique binary representation known as two's complement. You could do something like the following to accommodate:
private static void binary(int userNum) {
int remainder;
// while (userNum <= 1) {
// System.out.print(userNum);
// return;
// }
if (userNum == 0) {
return;
}
// simply mask off the bit instead of dividing by two
remainder = userNum & 1;
// and shift right thru the sign bit
binary(userNum >>> 1);
System.out.print(remainder);
}
}
binary(-6));
prints
11111111111111111111111111111010
And the reason these printed out in proper order is because your routine is recursive. That is a natural behavior of printing the values stored in the stack from a recursive procedure.
import java.util.Scanner;
public class Reverse_BinaryNum {
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner(System.in);
int inputNum;
System.out.println("Enter the Digit : ");
inputNum = scnr.nextInt();
System.out.println("The Reverse Binary for the given Digit is : ");
while (inputNum > 0) {
System.out.print(inputNum % 2);
inputNum = inputNum / 2;
}
scnr.close();
}
}
import java.util.Scanner;
public class Test1C
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
System.out.print("Enter an integer between 1 and 50: ");
double quo;
int num = reader.nextInt();
for(double a = 1; a <= num; a++)
{
quo = (num / a);
System.out.println(quo);
}
}
}
This is the code I currently am making to evaluate the list of quotients based on what number was inputted. Now the only thing my brain keeps farting on about is how to convert the whole numbers that are currently decimals into integers. However, the doubles (ex: 1.333) that are printed by this code are fine as is. I just can't figure out how to convert the whole number decimals (ex: 12.0) into whole number integers. Can someone help me?
yes you can :
String s = "1.333";
double d = Double.parseDouble(s);
int i = (int) d;
or
String s="1.333";
int i= new Double(s).intValue();
you can do like that .
Double d = new Double(1.25);
int i = d.intValue();
System.out.println("The integer value is :"+ i);
There is no general way to detect whether a double is truly an integer and a comparison of double and double or int must, generally, be handled with much care, but for the range of numbers in your program (and the upper bound could be raised considerably), this will work as you want:
for(double a = 1; a <= num; a++) {
double quo = num/a;
int iquo = (int)quo;
if( iquo == quo ){
System.out.println(iquo);
} else {
System.out.println(quo);
}
}
I tried to do it but i'm getting 1.0 as answer every time i run it. I'm not being able to find out what's wrong please help me. Here are the codes:
import java.util.Scanner;
public class Number23 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n=0;
float sum = 0,r = 0;
System.out.print("Enter a number for n: ");
n = input.nextInt();
for(int x = 1; x <= n; x++)
{
r = (1/x);
sum = sum + r;
}
System.out.print("The sum is "+sum);
}
}
In order to produce a reciprocal that has a floating point value it is not enough to declare r a float: the expression you assign it needs to be float as well. You can do it by using the f suffix on the constant 1 which you divide by x:
r = (1f / x);
Without the suffix, your expression represents an integer division, which produces an integer result, and drops the fraction. In your case, the only time that you get a value other than zero is when x is equal to 1.
class reciprocal
{
public static void main ( int n)
{
float i,a,s=0;
for(i=1;i<=n;i++)
{
a= 1/i;
s+=a;
}
System.out.print( "sum is "+s);
}
}
I need to find the smallest number which digit numbers product is equal to a given num.
import java.util.Scanner;
class timus_1014_2 {
public static void main(String[] args){
int[] arr = new int[10]; // eskan ban# chem imanum inchi a statik,
int prod = 1;
int j = 0;
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for (int i = 2; i < 10; ++i){
if (n % i == 0) {
arr[j] = i;
j++;
}
}
prod = prod * arr[j];
System.out.print(prod);
}
}
Something is wrong with the logic, whats is the problem when I input 10 it should give 25 but it gives 0. Please give ideas of how to make a program find a number which digits product is a given num.
If I understood your problem correctly you need a number whose product of digits equals a number N. Since you asked for new algorithm , you can chck following code.
Logic:
Note : For number whose prime factors are less than 10
Get all factors from 9 -> 2
add to list
print in reverse or use stack instead of list
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number");
int num = in.nextInt();
List<Integer> lst = new ArrayList<>();
for (int p = 9; p >= 2; p--) {
while (num % p == 0) {
num /= p;
lst.add(p);
}
}
String smallestNumber = "";
for (int i = lst.size() - 1; i >= 0; i--) {
smallestNumber = smallestNumber + lst.get(i);
}
System.out.println("Smallest number : " + smallestNumber);
}
}
Output :
Enter number
10
Smallest number : 25
Enter number
144
Smallest number : 289
Enter number
12
Smallest number : 26
I suggest you look at each error is fix it one by one. I also suggest you use an IDE which will show you the errors and you type and will help ensure you don't have an overwhelming number of errors and you can see if those error disappear based on your corrections.
BTW Often when you use an array for a short piece of code, it can often be eliminate as I suspect it can be removed in your case.
Static methods can not access non-static members of class.
In your case prod is member variable of class but not static. To fix the error , try to make prod as static.
private static int prod = 1;
I would prefer , to make it local variable if no other method is using it.
The problem here is you need to create an object of the particular class to call a particular method associated with it
import java.util.Scanner;
class DigPro {
static int[] arr = new int[10]; // eskan ban# chem imanum inchi a statik,
int prod = 1;
public static void main(String[] args){
Scanner in = new Scanner(System.in);
DigPro obj = new DigPro();
obj.prime(in.nextInt());
}
public void prime(int n){
for (int i = 1; i < 10; ++i){
for (int j = 0; j < 9; ++j) {
if (n % i == 0) {
arr[j] = i;
}
prod = prod * arr[j];
}
}
System.out.print(prod);
}
}
Here you need to create an object say obj of DigPro class and then call prime(int n) method with that object. Also your division is startint with zero which is changed to one
In above code you are increasing j after the assigning value to arr[j].You should do the following:-
prod = prod * arr[j-1];
Here it will multiply prod with last array updated. That is why you are getting zero. And for your another question find the smallest number which digit numbers product is equal to a given num has similar answer at this link.
Since this is actually a pretty interesting problem, I took the time to come up with a correct solution for all possible integer inputs.
import java.util.*;
public class Main{
public static void main(String[] args) {
System.out.println("Enter number:");
int number = new Scanner(System.in).nextInt();
Stack<String> factors = new Stack<>();
if(number==0){
factors.push("0");
}else if(number==1){
factors.push("1");
}else{
for(int f=9;f>1;f--){
while(number%f==0){
factors.push(Integer.toString(f));
number/=f;
}
}
}
if(number<0){
factors.push("-");
}
if(number>9){
System.out.println("This is impossible.");
}else{
System.out.println("Smallest Number:");
while(!factors.empty()) System.out.print(factors.pop());
}
}
}
I am trying to develop code for SPOJ factorial problem number 11. The following is my code
import java.math.*;
import java.io.*;
public class Problem11 {
/**
* Count the number of zeroes at the end of
* the factorial value of a number.
*/
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int numOfInputs=0;
numOfInputs=Integer.parseInt(br.readLine());
BigInteger nextNum[]=new BigInteger[numOfInputs];
BigInteger factValue[]=new BigInteger[numOfInputs];
//Get all the numbers to be computed
for(int count=0;count<numOfInputs;count++)
{
nextNum[count]=new BigInteger(br.readLine());
}
//Obtain the factorial value for each number
for(int count=0;count<numOfInputs;count++)
{
factValue[count]=getFact(nextNum[count]);
}
//Obtain the number of trailing zeroes
for(int count=0;count<numOfInputs;count++)
{
//System.out.println(factValue[count]);
System.out.println(getZeroes(factValue[count]));
}
}
public static String getZeroes(BigInteger num)
{
int numOfZeroes=0;
while(num.remainder(BigInteger.TEN).equals(BigInteger.ZERO))
{
num=num.divide(BigInteger.TEN);
numOfZeroes++;
}
return String.valueOf(numOfZeroes);
}
public static BigInteger getFact(BigInteger num)
{
BigInteger factorial=BigInteger.ONE;
if(num.equals(0))
{
return (BigInteger.valueOf(1));
}
else
{
int count=1;
while((BigInteger.valueOf(count).compareTo(num))<=0)
{
factorial=factorial.multiply(BigInteger.valueOf(count));
count++;
}
}
return factorial;
}
}
The code works fine for numbers up to 5 digits with small delay and for the last number
8735373 it is taking too much time, if I submit my solution, the judge shows compilation error.. I am unable to figure out whats the error. Please have a look at my code and help me to trace the problem.
You might look at this method for finding the number of trailing zeros in n!.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = in.nextInt();
for (int i = 0; i < count; i++) {
int n = in.nextInt();
int result = 0;
for (int d = 5; d <= n; d *= 5) {
result += n / d;
}
System.out.println(result);
}
}
}
Your approach (naive: counting the real factorial value and then counting the zeros manually) would NEVER pass no matter how. Take a look at the extreme case (i.e. upper limit of the factorial, I don't even think the given memory limit is enough to compute it). Look at the problem from different way, think what the real problem is, that's the art of problem solving ;)
Hint: what can produce and add more 0s to the end of a number, specifically by multiplication?
The reason for your error is it should be public class Main
Also your code will get TLE, you must observe that brute force will never work on SPOJ. The way to solve this is to see an interesting pattern with powers of 5 and the number of zeroes at the end.
Here is a solution in C. We don't need to compute the exact factorial for this problem.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 1000000
int xpn(int x, int n){
int prod=1;
while(n){
prod*=x;
n--;
}
return prod;
}
int trail(int x){
int numZero=0;
int i=1;
int k;
for(;x/xpn(5,i);i++){
numZero+=(x/xpn(5,i));
}
return numZero;
}
int main(int argc, char **argv){
#if 1
int n;
int num[MAX];
int zero[MAX];
scanf("%d",&n);
int count=n;
int i=0;
while(count){
scanf("%d",&num[i]);
zero[i]=trail(num[i]);
printf("%d\n",zero[i]);
i++;
count--;
}
#endif
return 0;
}
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner s = new Scanner(System.in);
int t = s.nextInt();
while (t-->0){
int n = s.nextInt();
int count = 0;
while(n>0){
count +=n/5;
n/=5;
}
System.out.println(count);
}
}
}
This solution will work absolutely fine.
Let me explain it.
When you refer to quantitative aptitude there is a short formula for calculating the number of trailing zeroes for any factorial number. Divide the number directly by 5 and start adding quotient and then divide quotient with 5 and again add until the value start giving constant quotient. Refer to below example. If you don't even understand refer to quantitative aptitude from any source.
e.g.
1. 60! 60/5 = 12, 12/5 = 2, add all the quotient i.e equals to 14.
2. 500! 500/5 = 100, 100/5 = 20, 20/5 = 4, ans = 124.