I have searched the site, and though it has been answered many times, I still have one more question.
I have the code to do the factorial with recursion. I am just having trouble with the easiest part of it.
When printing, my project requires that it should print:
4! is equal to 4 x 3 x 2 x 1 = 24
How do I get a for loop, or recursive way to get the "(4 x 3 x 2 x 1)" to work with any value of n?
import java.util.Scanner;
public class Factorial
{
public static void main(String args[])
{
System.out.println("Enter an integer:");
Scanner keyboard= new Scanner(System.in);
int num=keyboard.nextInt();
System.out.print(num+ "!"+ " is equal to ");
Print(num);
System.out.print(FactorialCalc(num));
}
public static double FactorialCalc(int number)
{
double result;
if(number<=1)
{
result= 1;
return result;
}
else
{
return result= number * FactorialCalc(number-1);
}
}
public static void Print(int n)
{
for(int i=n; i<=0;i--)
{
System.out.print(n + 'x' + (n-1));
}
}
}
public static void Print(int n) {
for (int i = n; i > 0; i--) {
System.out.print(i);
if (i == 1) {
System.out.print("=");
continue;
}
System.out.print("x");
}
}
And the output:
Enter an integer:
4
4! is equal to 4x3x2x1=24.0
A very simple solution using a for loop will be
int fact=1;
for(int i=1;i<n;i++)
fact=fact*i;
Your code works, you only forgot one thing:
Which is the variable used for counting the iterations of the for loop in the Print method? What are its values inside the loop?
public static void Print(int n)
{
for(int i=n; i<=0;i--) //i minor or equal 0? When does the loop need to finish?
//What happens if you multiply something with 0?
{
System.out.print(n + 'x' + (n-1));
}
}
Try to get it on your own, but if you can't...
...the problem is that you're printing n instead of i. In the loop, the variable that is decremented is i via i--. It starts from num and gets smaller and smaller... That's what you need to print!
Changhe the print to:
System.out.print(i + "x");
Your task is to get rid of the last printed x! ;D
As per the loop condition, your loop must stop when i reaches 1 to have
(num) x (num-1) x .. x 2 x 1 (no 0!!)
So the condition will be for(int i = n; i >= 1;i--)
You could incorporate printing the list of multiplied values directly into the recursion rather than adding a looping print. Put appropriate print() statements in both the if and else clauses of your recursion. For the former, just print "1 = ". For the latter, print number + " x ".
You don't actually need the local variable result. I'd also recommend using Java conventions regarding capitalization: method names should begin with a lower case letter, upper case indicates a class or interface. Finally, I changed the return type to long because factorials are integer-based, even though they can quickly get big.
import java.util.Scanner;
public class Factorial {
public static long printFactorial(int number) {
if(number <= 1) {
System.out.print("1 = ");
return 1;
} else {
System.out.print(number + " x ");
return number * printFactorial(number-1);
}
}
public static void main(String args[]) {
System.out.print("Enter an integer: ");
Scanner keyboard= new Scanner(System.in);
int num=keyboard.nextInt();
System.out.print(num + "! is equal to ");
System.out.println(printFactorial(num));
}
}
Related
Everything runs fine in my Java code except at the very end of the code. So basically I can't figure out how to print out the User's Number if it is the same. For example I am prompt the User for a starting number and an ending number (integers). So say the user enters in the same integer "10" for starting number and "10" for ending number. I want the output to only be "10" to be printed only just once. I've tried everything I can think of with trying While Loop, Do-While Loop, and For Loops but I just can't figure it out?
------------------------JAVA CODE BELOW-------------------------------------------
import java.util.Scanner;
public class LoopsAssignment {
public static void main(String[] args) {
// input Scanner
Scanner input = new Scanner(System.in);
// ask user for a starting number and a ending number
System.out.println("Now I'll print whatever numbers you'd like!");
System.out.println("Give me a starting number: ");
startNum = input.nextInt();
System.out.println("Give me an ending number: ");
endNum = input.nextInt();
// count the users range of numbers
System.out.println("I counted your range of numbers: ");
int a = startNum;
int b = endNum;
while (a <= b) {
System.out.println(a);
a = a + 1;
}
while (a >= b) {
System.out.println(a);
a = a - 1;
}
while (a == b) {
System.out.println(a);
}
}
}
---------------------OUT PUT BELOW -----------------------------------------------------
Now I'll print whatever numbers you'd like!
Give me a starting number:
10
Give me an ending number:
10
I counted your range of numbers:
10
11
10
----jGRASP: operation complete.
You could restructure your code as follows:
while (a < b) {
System.out.println(a);
a = a + 1;
}
while (a > b) {
System.out.println(a);
a = a - 1;
}
if (a == b) {
System.out.println(a);
}
You can use for loop:
public static void printRange(int minInclusive, int maxInclusive) {
for (; minInclusive <= maxInclusive; minInclusive++)
System.out.println(minInclusive);
}
So you are either counting up, down or there's just one.
So
int step = endNum>startNum ? +1 : -1;
int a = startNum;
int b = endNum;
while (a != b) {
System.out.println(a);
a = a + step;
}
System.out.println(b);
Or put a break in the middle of a for loop. Also there's +=, and a few things we can make more conventional.
int step = endNum>startNum ? +1 : -1;
for (int i=startNum; ; i+=step) {
System.out.println(i);
if (i == endNum) {
break;
}
}
The issue is in your first two while loops where you are using ">=" and "<=". You can remove "=" from the condition.
However you can improve your code as suggested in other comments.
I tried to write a simple java program which counts how many odd digits there are inside a number (for example, for input "123" the program should return 2). The program instead returns all the digits of the given number. Any idea?
import java.util.*;
//Counts the number of odd digits in an int using recursion
public class OddCount{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Digit a positive int number: ");
int n = in.nextInt();
System.out.println("The number of odd digits is " + oddDigitCounter(n));
}
public static int oddDigitCounter(int number) {
int result = 0;
if(number<=10){
if(number%2==0)
result = 0;
else
result++;
}
else{
if(number%10!=0){
if((number%10)/2!=0)
result = 1 + oddDigitCounter(number/10);
else
result = 0 + oddDigitCounter(number/10);
}
else{
result = 0 + oddDigitCounter(number/10);
}
}
return result;
}
}
Here is a way to write your recursive method without all the unnecessary conditions.
public static int oddDigitCounter(int number) {
if (number==0) {
return 0;
}
return (number&1) + oddDigitCounter(number/10);
}
Using &1 instead of %2 allows it to work for negative numbers as well as positive ones.1
1 (number&1) is zero for an even number, and one for an odd number, and works regardless of whether the number is positive or negative. For instance, if number==-3 then (number%2)==-1, but (number&1)==1, which is what we want in this case.
Check your code, you are using / instead of % in this if condition:
if((number%10)/2!=0)
It should be:
if((number%10)%2!=0)
In oddDigitCounter() why don't you simply check digit by digit if it's an even or odd one and echo (store) the result?
Recursive approach: at first call you may pass to the function the entire number and then if the number is 1 digit long let the function do the check and return, otherwhise do the check against the 1st digit and pass the others again to the function itself.
Procedural approach: do a simple loop through the digits and do the checks.
You can use following sample:
import java.util.Scanner;
public class NumberOfOddDigist {
private static int count = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Digit a positive int number: ");
int n = in.nextInt();
countOdd(n);
System.out.println("The number of odd digits is " + count);
in.close();
}
public static void countOdd(int number) {
int remainder = number % 10;
int quotient = (number - remainder) / 10;
if (!(remainder % 2 == 0)) {
count++;
}
number = quotient;
if (number < 10) {
if (!(number % 2 == 0)) {
count++;
}
} else {
countOdd(number);
}
}
}
Hi very first Java class and it seems to be going a mile a minute. We learn the basics on a topic and we are asked to produce code for more advanced programs than what helped us get introduced to the topic.
Write a recursive program which takes an integer number as Input. The program takes each digit in the number and add them all together, repeating with the new sum until the result is a single digit.
Your Output should look like exactly this :
################### output example 1
Enter a number : 96374
I am calculating.....
Step 1 : 9 + 6 + 3 + 7 + 4 = 29
Step 2 : 2 + 9 = 11
Step 3 : 1 + 1 =2
Finally Single digit in 3 steps !!!!!
Your answer is 2.
I understand the math java uses to produce the output I want. I can do that much after learning the basics on recursion. But with just setting up the layout and format of the code I am lost. I get errors that make sense but have trouble correcting with my inexperience.
package numout;
import java.util.Scanner;
public class NumOut {
public static void main(String[] args) {
System.out.print("Enter number: ");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println(n);
}
public int sumDigit(int n){
int sum = n % 9;
if(sum == 0){
if(n > 0)
return 9;
}
return sum;
}
}
The output understandably duplicates the code given by the input from the user.
I had trouble calling the second class when I tried to split it up into two. I also know I am not soprln n, or the sum. So I try to make it into one and I can visibly see the problem but am unaware how to find the solution.
Think of recursion as solving a problem by breaking it into similar problems which are smaller. You also need to have a case where the problem is so small that the solution is obvious, or at least easily computed. For example, with your exercise to sum the digits of a number, you need to add the ones digit to the sum of all the other digits. Notice that sum of all the other digits describes a smaller version of the same problem. In this case, the smallest problem will be one with only a single digit.
What this all means, is that you need to write a method sumDigits(int num) that takes the ones digit of num and adds it to the sum of the other digits by recursively calling sumDigits() with a smaller number.
This is how you need to do : basically you are not using any recursion in your code. Recursion is basically function calling itself. Don't be daunted by the language, you will going to enjoy problem solving once you start doing it regularly.
public static void main(String []args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
printSingleDightSum(n);
}
public static void printSingleDightSum(int N) {
int sum = 0;
int num = N;
while(num !=0 ){
int a = num%10;
sum + = a;
num = num/10;
}
if(sum < 10) {
System.out.println('single digit sum is '+sum);
return;
} else {
printSingleDightSum(sum);
}
}
Here is the code, I will add comments and an explanation later but for now here is the code:
package numout;
import java.util.Scanner;
public class NumOut {
public static void main(String[] args) {
System.out.println("################### output example 1");
System.out.print("Enter number: ");
final int n = new Scanner(System.in).nextInt();
System.out.print("\nI am Calculating.....");
sumSums(n, 1);
}
public static int sumSums(int n, int step) {
System.out.print("\n\nStep " + step + " : ");
final int num = sumDigit(n);
System.out.print("= " + num);
if(num > 9) {
sumSums(num, step+1);
}
return num;
}
public static int sumDigit(int n) {
int modulo = n % 10;
if(n == 0) return 0;
final int num = sumDigit(n / 10);
if(n / 10 != 0)
System.out.print("+ " + modulo + " ");
else
System.out.print(modulo + " ");
return modulo + num;
}
}
So what my program is supposed to do...
Iterate through an array of 113 numbers
Print said numbers
But if..
number is odd print "odd" beside it
number is divisible by 5 print "hi five"
total number of x and its subsequent number (x+1) is divisible by 7 print "wow"
number is prime print "prime"
Currently my program will iterate through the numbers and print the ones that apply, and if two apply it will print it twice with different notes. What i would like to do is have it print all the numbers, then print the notes beside the numbers that apply. And if two conditions apply, print the notes beside each other and not on new lines.
ex. of what i would like it to do..
x: 5, odd, high five
Ive been trying different techniques from some examples i found but to no avail. Any direction or guidance would be greatly appreciated!
P.S. - i know i haven't implemented prime yet, my equation isn't right, thats next on my list.
Here is what i have so far..
import java.util.ArrayList;
public class Number {
public static ArrayList<Integer> getSequence() {
ArrayList<Integer> numbers = new ArrayList<Integer>(113);
for (int n = 0; n <= 113; n++) {
numbers.add(n);
}
return numbers;
}
public static boolean isOdd(int n) {
if (getSequence().get(n) % 2 != 0) {
System.out.println("x: " + n + ", x is odd");
}
return true;
}
public static boolean isDivisibleBy5(int n) {
if (getSequence().get(n) % 5 == 0) {
System.out.println("x: " + n + ", hi five");
}
return true;
}
public static boolean isDivisibleBy7(int n) {
int x = getSequence().get(n) + (getSequence().get(n) + 1);
if (x % 7 == 0 && x<113) {
System.out.println("x: " + n + ", wow");
}
return true;
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(n); i++) {
System.out.println("x: " + n + ", prime");
if (n % 1 == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
ArrayList<Integer> nums = getSequence();
for (int n : nums) {
if(isOdd(n)) {
}
if(isDivisibleBy5(n)){
}
if(isDivisibleBy7(n)){
}
}
}
}
Instead of using Integer arraylist create a separate class which can hold Integer and ArrayList<String>. Then create your arraylist of that class type.
Make methods in your new class as follows
Method to insert the number
Method to retrieve the number
Method to insert a label to the array list.
Method to retrieve the ArrayList or String[]
This way you can easily overcome your problem.
One other method is to use a Map object(HashMap instead). Integer as the KEY and ArrayList<String> as the VALUE.
How do I make my program to stop at the user's input?
Here is my code:
public class H {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input x: ");
int x = input.nextInt();
for (int i = 0; i < x; i++) {
if (i < x)
System.out.print(printFib(i) + " ");
else if (i > x)
break;
}
}
public static int printFib(int number) {
if (number == 0 || number == 1)
return number;
else
return printFib(number - 1) + printFib(number - 2);
}
}
So, if I enter 10 my program should stop before the number. Example:
Input: 10
Output: 0 1 1 2 3 5 8
But instead I get 0 1 1 2 3 5 8 13 21 34
How can I fix it?
int x = input.nextInt();
int fib = 0;
while (fib < x){
System.out.print(printFib(fib)+ " ");
fib++;
}
}
Don't use a for loop which right now you're using to print out Fibonacci numbers until the number of items printed is less than the entered number. Instead use a while loop that stops when the Fibonacci number itself is greater than the entered number.
Since this is likely homework, I'm just going to give this suggestion and not a code solution, but please give a solution a try, and if still stuck, come back with questions.
Pseudocode
Get value of x
create fibonacci variable and assign it 0
while fibonacci is less than x
display current fibonacci number
calculate next fibonacci number and place in variable
end while loop
public class H {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input x: ");
int x = input.nextInt();
int i = 0;
while ( printFib(i) <= x ) {
System.out.print(printFib(i) + " ");
i ++ ;
}
}
public static int printFib(int number) {
if (number == 0 || number == 1)
return number;
else
return printFib(number - 1) + printFib(number - 2);
}
}
While the number return from the printFib() method is less than and equal to the user input, it then runs the method. I've tried the code and it works.