My Code doesn't print out Triangular Numbers according to the formula, but only loops the number 1.
What is my mistake?
public class Triangular{
public static void main(String[] args) {
int n = 1;
int t = (n * (n + 1)) / 2;
while(n <= 10) {
n++;
System.out.println(t);
}
}
}
Although you are increasing n by one, you are not recalculating the value of t inside the loop.
Try calculating the value of t inside the loop, for example:
public static void main(String[] args)
{
int n = 0;
int t = 0;
while (n <= 10)
{
n++;
t = (n * (n + 1))/2;
System.out.println(t);
}
}
Each time you increase the value of n, you need to recalculate the value of t by passing the new value of n into the formula.
t is not recalculated when n changes. You need to assign it inside the while loop. Also, you may as well just do this:
public class Triangular {
public static void main(String[] args) {
int n = 1;
int t = 1;
while(n <= 10) {
System.out.println(t);
n++;
t += n;
}
}
}
Related
This is my code and I do not know why the answer after 12 are incorrect.
First i calculate the Factorial of input number then I have to show the least valuable digit.
public class q3411 {
public static int leastValuableDigit(int n) {
for(int i = 0; i < String.valueOf(n).length(); i++) {
int x = (int) Math.floor((n % Math.pow(10, i + 1)) / Math.pow(10, i));
if(x != 0) return x;
}
return -1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int fon = 1;
for(int i = 1; i <= n; i++) fon *= i;
System.out.println((leastValuableDigit(fon)));
}
}
First, I changed the algorithm of finding the factorial for more numbers.
The algorithm of finding the required number can be changed by removing all 0 from the factorial and taking the last of its bytes.
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static byte leastValuableDigit(BigInteger n) {
String num = String.valueOf(n).replaceAll("0", "");
return Byte.parseByte(String.valueOf(num.charAt(num.length() - 1)));
}
public static BigInteger getFactorial(int f) {
if (f <= 1) {
return BigInteger.valueOf(1);
}
else {
return BigInteger.valueOf(f).multiply(getFactorial(f - 1));
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
BigInteger fon = getFactorial(n);
System.out.println((leastValuableDigit(fon)));
}
}
Your algorithm is incorrect, cause you do a lot of unnecessary calculations and roundings
How do I make a function return the sum of all digits until it becomes a 1 digit number, using recursion? I was able to make a function that gets the sum of all digits, but cant seem to find a way to recursively sum the digits of the sum itself:
class sum_of_digits
{
static int sum_of_digit(int n)
{
if (n == 0)
return 0;
return (n % 10 + sum_of_digit(n / 10));
}
public static void main(String args[])
{
int num = 12345;
int result = sum_of_digit(num);
System.out.println("Sum of digits in " +
num + " is " + result);
}
}
This code prints the sum of '12345', which is 15. But I need to change it so it prints the sum of 1 + 5, which is 6.
do you think it is possible to make it work without an additional
method?
Why can't we just let the recursion do the work for us and simply say:
static int sum_of_digit(int n)
{
if (n < 10)
return n;
return sum_of_digit(n % 10 + sum_of_digit(n / 10));
}
Things will become a lot easier if you define an additional recursive "layer" in conjunction with sum_of_digit. This new function can call sum_of_digit until it has a single digit as a result. Here is what I mean:
static int sum_to_one_digit(int n) {
if(n/10 == 0) return n;
return sum_to_one_digit(sum_of_digit(n));
}
The code from main will be:
public static void main(String args[])
{
int num = 12345;
int result = sum_to_one_digit(num);
System.out.println("Sum of digits in " +
num + " is " + result);
}
You could add a clause at the end to check whether the sum is smaller than 10, if it isn't then recursively call it again with the newly calculated sum, ie.
static int sum_of_digit(int n)
{
if (n == 0)
return 0;
int temp = (n % 10 + sum_of_digit(n / 10));
if (temp < 10)
return temp;
return sum_of_digit(temp);
}
There are several ways to do it, one would be like this if global variables are allowed :
public class Sum_of_digits{
static int sum = 0;
public static void main(String args[]){
int n = 12345;
System.out.println(sum_of_digit(n));
sum = 0;
}
static int sum_of_digit(int n){
if(n==0){
if(sum/10 == 0){
return sum;
}else{
n=sum;
sum=0;
}
}
sum = sum+(n%10);
n=n/10;
return sum_of_digit(n);
}
}
and if Global variable are not allowed then passing sum as a parameter will help :
public class Sum_of_digits{
public static void main(String args[]){
int n = 12345;
int sum = 0;
System.out.println(sum_of_digit(n,sum));
}
static int sum_of_digit(int n,int sum){
if(n==0){
if(sum/10 == 0){
return sum;
}else{
n=sum;
sum=0;
}
}
sum = sum+(n%10);
n=n/10;
return sum_of_digit(n,sum);
}
}
Here we are just shifting the focus from n to sum to evaluate the condition when the loop/recursion will terminate.
I wrote this program using return but would like the program to do the exact same thing only using the run-method and a for-loop. It should print the n-th number in the Fibonacci sequence.
import acm.program.*;
public class TESTfibonacci extends ConsoleProgram {
public void run() {
long n = readInt("Enter a number: ");
println(fibo(n));
}
// Prints the n-th Fibonacci number.
long fibo(long n) {
if (n == 0) {
return 0;
} else if (n <= 2) {
return 1;
} else {
return fibo(n - 2) + fibo(n - 1);
}
}
}
you can use dynamic programming for this. The code is taken from here
class Fibonacci {
static int fib(int n) {
/* Declare an array to store Fibonacci numbers. */
int f[] = new int[n + 2]; // 1 extra to handle case, n = 0
int i;
/* 0th and 1st number of the series are 0 and 1*/
f[0] = 0;
f[1] = 1;
for (i = 2; i <= n; i++) {
/* Add the previous 2 numbers in the series
and store it */
f[i] = f[i - 1] + f[i - 2];
}
return f[n];
}
public static void main(String args[]) {
int n = 9;
System.out.println(fib(n));
}
}
I need to implement a recursive method printDigits that takes an integer num as a parameter and prints its digits in reverse order, one digit per line.
This is what I have so far:
public class PrintDigits {
public static void main(String[] args) {
System.out.println("Reverse of no. is " + reversDigits(91));
}
/* Recursive function to reverse digits of num */
public static int reversDigits(int number) {
if (number == 0)
return number;
else {
return number % 10;
}
}
}
I feel like there is only one line of code that I am missing, but not sure what I need to do to fix it.
public static void main(String[] args) {
reverseDigits(98198187);
}
/* Recursive function to reverse digits of num */
public static void reverseDigits(long number) {
if (number < 10) {
System.out.println(number);
return;
}
else {
System.out.println(number % 10);
reverseDigits(number/10);
}
}
This doesn't exactly answer the question, but it actually computes the entire reversed number instead of printing the digits as they are calculated. The result is an int with the digits in reversed order. Much more powerful than printing out the string version of the numbers one by one:
public class Reverse {
public static void main(String[] args) {
// input int parameter
int param = Integer.parseInt(args[0]);
System.out.println(reverse(param));
}
public static int reverse(int input) {
return reverse(input, 0);
}
private static int reverse(int original, int reversed) {
// get the rightmost original digit and remove it
int rightmost = original % 10;
original -= rightmost;
original /= 10;
// add rightmost original digit to left of reversed
reversed += rightmost * Math.pow(10, numDigits(original));
return (original == 0)
? reversed
: reverse(original, reversed);
}
public static int numDigits(int number) {
number = Math.abs(number);
if (number >= 10) {
return 1 + numDigits(number /= 10);
} else if (number > 0) {
return 1;
} else {
return 0;
}
}
}
public static void reversDigits(long number) {
System.out.println(number % 10);
if (number >= 10) {
reversDigits(number / 10);
}
}
This is shortest/simplest version so far;)
public static int reversDigits(int num) {
if(num < 1) {
return 0;
}
int temp = num % 10;
num = (num - temp)/10;
System.out.println(temp);
return reversDigits(num);
}
This will print the digits one at a time in reverse order. You don't need to do System.out in your main method.
I found I had to pick off the highest digit (on the left) and work towards the rightmost digit. I couldn't get a recursive one to work going from right to left.
public static int reverseItRecursive(int number)
{
if (number == 0)
return 0;
int n = number;
int pow = 1;
while (n >= 10)
{
n = n / 10;
pow = pow * 10;
}
return (n + reverseItRecursive(number - n*pow)*10);
}
This should work
int rev = 0;
int reverse(int num)
{
if (num < 10) {
rev = rev*10 + num;
}
else {
rev = rev*10 + (num % 10);
num = reverse(num / 10);
}
return rev;
}
//Try out this, recursion with singe variable using Math class.
public static void main(String[] args) {
// Let the number be 139
int n=139;
System.out.println("reverse is "+rev(n));
}
static int rev(int n){
if (n==0)return 0;
else {
return n%10*(int) Math.pow(10,(double) (int)Math.log10(n))+rev(n/10);
}
}
This method reverse the integer and returns the result without using any string functions, Math, or by just printing
public class ReverseNumber {
public static void main (String[] args) {
ReverseNumber rNumber = new ReverseNumber();
System.out.println(rNumber.reverseRecursive(1234,0)); // pass zero to initialize the reverse number
}
public int reverseRecursive(int n, int reverse) {// n - the number to reverse
// System.out.println(n);
if (n != 0){
reverse = reverse * 10;
reverse = reverse + n %10;
n = n/10;
} else {
return reverse;
}
return reverseRecursive(n,reverse);
}}
public void reverse(int num){
System.out.print(num %10);
if(num / 10 == 0){
return;
}
reverse(num /10);
return;
}
This is very shortest/simplest way in two lines code:
public static int reverseNumber(int n)
{
System.out.println(n % 10);
return (n/10 > 0) ? reverseNumber(n/10) : n;
}
I came looking for a more elegant version than mine, but perhaps this just requires a bit of a messy algorithm. Mine also returns the actual integer value which I agree is much more useful than only printing the string:
Mine:
public static int reverse(int n){
if(n<10)return n;
return n%10*(int)Math.pow(10,(int)Math.log10((double)n)) + reverse(n/10);
}
so this returns the last digit, multiplied by 10^current power + (recursive call)
Here you go :
static String reverseDigits(int n)
{
String N = "";
if ( n== 0)
return N;
else
{
N += n%10;
return N + reverseDigits(n/= 10);
}
}
This is of course returned as String.
If you want it as int all you have to do is parse it using Integer.parseInt()
//Reverse a number using recursion by bibhu.rank
public class Rev_num {
public static int revnum(int x){
int temp1=x,temp2=1;
if(x<10){
return x;
}
while(temp1>=10){
temp2*=10;
temp1/=10;
}
if(((x%temp2) < (temp2/10))&& x%temp2!=0){
int c=temp2;
while(c> x%temp2){
c/=10;
}
c=temp2/c;
temp2=x%temp2;
return((temp1)+(c*revnum(temp2)));
}
temp2=x%temp2;
return (temp1+(10*revnum(temp2)));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter a number");
Scanner y=new Scanner(System.in);
System.out.println(revnum(y.nextInt()));
y.close();
}
}
public class reverseIntRec{
public static void main(String args[]) {
System.out.println(reverse(91));
}
public static int reverse(int x) {
String strX = String.valueOf(x);
if (Math.abs(x) < 10)
return x;
else
return x % 10 * ((int) Math.pow(10, strX.length()-1)) + reverse(x/10);
}
}
Here is my answer return as integer. I converted x into string to see how many 0s you should multiply with.
For example: reverse(91) returns 1 * 10 + reverse (9), and that returns 10 + 9 = 19.
Relatively simple since you need to print one digit per line. You also state that you print its digits, which implies that leading zeros are still going to be displayed. Our test case
123000 prints :
0
0
0
3
2
1
here is the code, no while, no string, and no math library :
private void printIntegerDigitsReversed(int i) {
if (i / 10== 0 ){
System.out.println(i);
}
else{
printIntegerDigitsReversed(i%10);
printIntegerDigitsReversed(i/10);
}
}
I tried to find the factorial of a large number e.g. 8785856 in a typical way using for-loop and double data type.
But it is displaying infinity as the result, may be because it is exceeding its limit.
So please guide me the way to find the factorial of a very large number.
My code:
class abc
{
public static void main (String[]args)
{
double fact=1;
for(int i=1;i<=8785856;i++)
{
fact=fact*i;
}
System.out.println(fact);
}
}
Output:-
Infinity
I am new to Java but have learned some concepts of IO-handling and all.
public static void main(String[] args) {
BigInteger fact = BigInteger.valueOf(1);
for (int i = 1; i <= 8785856; i++)
fact = fact.multiply(BigInteger.valueOf(i));
System.out.println(fact);
}
You might want to reconsider calculating this huge value. Wolfram Alpha's Approximation suggests it will most certainly not fit in your main memory to be displayed.
This code should work fine :-
public class BigMath {
public static String factorial(int n) {
return factorial(n, 300);
}
private static String factorial(int n, int maxSize) {
int res[] = new int[maxSize];
res[0] = 1; // Initialize result
int res_size = 1;
// Apply simple factorial formula n! = 1 * 2 * 3 * 4... * n
for (int x = 2; x <= n; x++) {
res_size = multiply(x, res, res_size);
}
StringBuffer buff = new StringBuffer();
for (int i = res_size - 1; i >= 0; i--) {
buff.append(res[i]);
}
return buff.toString();
}
/**
* This function multiplies x with the number represented by res[]. res_size
* is size of res[] or number of digits in the number represented by res[].
* This function uses simple school mathematics for multiplication.
*
* This function may value of res_size and returns the new value of res_size.
*/
private static int multiply(int x, int res[], int res_size) {
int carry = 0; // Initialize carry.
// One by one multiply n with individual digits of res[].
for (int i = 0; i < res_size; i++) {
int prod = res[i] * x + carry;
res[i] = prod % 10; // Store last digit of 'prod' in res[]
carry = prod / 10; // Put rest in carry
}
// Put carry in res and increase result size.
while (carry != 0) {
res[res_size] = carry % 10;
carry = carry / 10;
res_size++;
}
return res_size;
}
/** Driver method. */
public static void main(String[] args) {
int n = 100;
System.out.printf("Factorial %d = %s%n", n, factorial(n));
}
}
Hint: Use the BigInteger class, and be prepared to give the JVM a lot of memory. The value of 8785856! is a really big number.
Use the class BigInteger. ( I am not sure if that will even work for such huge integers )
Infinity is a special reserved value in the Double class used when you have exceed the maximum number the a double can hold.
If you want your code to work, use the BigDecimal class, but given the input number, don't expect your program to finish execution any time soon.
The above solutions for your problem (8785856!) using BigInteger would take literally hours of CPU time if not days. Do you need the exact result or would an approximation suffice?
There is a mathematical approach called "Sterling's Approximation
" which can be computed simply and fast, and the following is Gosper's improvement:
import java.util.*;
import java.math.*;
class main
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int i;
int n=sc.nextInt();
BigInteger fact = BigInteger.valueOf(1);
for ( i = 1; i <= n; i++)
{
fact = fact.multiply(BigInteger.valueOf(i));
}
System.out.println(fact);
}
}
Try this:
import java.math.BigInteger;
public class LargeFactorial
{
public static void main(String[] args)
{
int n = 50;
}
public static BigInteger factorial(int n)
{
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++)
result = result.multiply(new BigInteger(i + ""));
return result;
}
}
Scanner r = new Scanner(System.in);
System.out.print("Input Number : ");
int num = r.nextInt();
int ans = 1;
if (num <= 0) {
ans = 0;
}
while (num > 0) {
System.out.println(num + " x ");
ans *= num--;
}
System.out.println("\b\b=" + ans);
public static void main (String[] args) throws java.lang.Exception
{
BigInteger fact= BigInteger.ONE;
int factorialNo = 8785856 ;
for (int i = 2; i <= factorialNo; i++) {
fact = fact.multiply(new BigInteger(String.valueOf(i)));
}
System.out.println("Factorial of the given number is = " + fact);
}
import java.util.Scanner;
public class factorial {
public static void main(String[] args) {
System.out.println("Enter the number : ");
Scanner s=new Scanner(System.in);
int n=s.nextInt();
factorial f=new factorial();
int result=f.fact(n);
System.out.println("factorial of "+n+" is "+result);
}
int fact(int a)
{
if(a==1)
return 1;
else
return a*fact(a-1);
}
}