I have written a simple program in java to find the factorial, which works fine. I am now trying to refine the output, but I'm not sure how to do it.
My Program:
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
int fact = 1;
Scanner number = new Scanner(System.in);
System.out.println("Enter the number : ");
int n = number.nextInt();
if (n < 0) {
System.out.println("Enter positive number");
} else {
System.out.print("Factorial Sequence is :");
for (int i = n; i >= 1; i--) {
fact = fact * i;
System.out.print(i + "*");
}
System.out.println("Factorial of number " + n + " is :" + fact);
}
}
}
Output shown is in this format (a single line, * after the 1):
Factorial Sequence is :5*4*3*2*1*Factorial of number 5 is :120
I want output in this format:
Factorial Sequence is :5*4*3*2*1
Factorial of number 5 is :120
Since 1 is not going to modify the factorial result your code can be rewriten as:
for (int i = n; i >= 2; i--) {
fact = fact * i;
System.out.print(i + "*");
}
System.out.println("1");
Another option is to use string concatenation during your for loop:
String s = "Factorial Sequence is :";
for (int i = n; i >= 1; i--) {
fact = fact * i;
s += i + (i > 1 ? "*" : "");
}
System.out.println(s);
Only 'benefit' this has over the other options is it saves calling System.out.print each iteration, at the expense of a string concatenation operation. Probably no performance difference at all, and certainly not significant here, but it is an alternate means to the same end.
EDIT: Use #demostene's excellent suggestion to avoid the final '*' after the final '1' - it avoids the conditional expression within the for loop, which is really nice as your factorial becomes larger.
To make the gap, you can add an \n literal to represent a newline.
System.out.println("\nFactorial of number " + n + " is :" + fact);
And for the last *, you can either remove it at the end or not add it if i is 1..
System.out.print(i + (i > 1?"*":""));
This says if i is greater than 1, return a *, otherwise return an empty string.
Just add a print line statement:
System.out.println(); // add this line
System.out.println("Factorial of number " + n + " is :" + fact);
Related
I'm really new to coding and just got assigned my first coding homework involving methods and returns. I managed to struggle through and end up with this, which I'm pretty proud of, but I'm not quite sure it's right. Along with that, my return statements are all on the same lines instead of formatted how my teacher says they should be ("n is a perfect number", then the line below says "factors: x y z", repeated for each perfect number. Below are the exact instructions plus what it outputs. Anything will help!
Write a method (also known as functions in C++) named isPerfect that takes in one parameter named number, and return a String containing the factors for the number that totals up to the number if the number is a perfect number. If the number is not a perfect number, have the method return a null string (do this with a simple: return null; statement).
Utilize this isPerfect method in a program that prompts the user for a maximum integer, so the program can display all perfect numbers from 2 to the maximum integer
286 is perfect.Factors: 1 2 3 1 2 4 7 14
It should be
6 is perfect
Factors: 1 2 3
28 is perfect
Factors: 1 2 4 7 14
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in) ;
System.out.print("Enter max number: ") ;
int max = input.nextInt() ;
String result = isPerfect(max) ;
System.out.print(result) ;
}
public static String isPerfect(int number) {
String factors = "Factors: " ;
String perfect = " is perfect." ;
for (int test = 1; number >= test; test++) {
int sum = 0 ;
for (int counter = 1; counter <= test/2; counter++) {
if (test % counter == 0) {
sum += counter ;
}
}
if (sum == test) {
perfect = test + perfect ;
for (int counter = 1; counter <= test/2; counter++) {
if (test % counter == 0) {
factors += counter + " " ;
}
}
}
}
return perfect + factors ;
}
}
Couple of things you could do:
Firstly, you do not need two loops to do this. You can run one loop till number and keep checking if it's divisible by the iterating variable. If it is, then add it to a variable called sum.
Example:
.
factors = []; //this can be a new array or string, choice is yours
sum=0;
for(int i=1; i<number; i++){
if(number % i == 0){
sum += i;
add the value i to factors variable.
}
}
after this loop completes, check if sum == number, the if block to return the output with factors, and else block to return the output without factors or factors = null(like in the problem statement)
In your return answer add a newline character between perfect and the factors to make it look like the teacher's output.
You can try the solution below:
public String isPerfect(int number) {
StringBuilder factors = new StringBuilder("Factors: ");
StringBuilder perfect = new StringBuilder(" is perfect.");
int sum = 0;
for (int i = 1; i < number; i++) {
if (number % i == 0) {
sum += i;
factors.append(" " + i);
}
}
if (sum == number) {
return number + "" + perfect.append(" \n" + factors);
}
return number + " is not perfect";
}
Keep separate variables for your template bits for the output and the actual output that you are constructing. So I suggest that you don’t alter factors and perfect and instead declare one more variable:
String result = "";
Now when you’ve found a perfect number, add to the result like this:
result += test + perfect + '\n' + factors;
for (int counter = 1; counter <= test/2; counter++) {
if (test % counter == 0) {
result += counter + " ";
}
}
result += '\n';
I have also inserted some line breaks, '\n'. Then of course return the result from your method:
return result;
With these changes your method returns:
6 is perfect.
Factors: 1 2 3
28 is perfect.
Factors: 1 2 4 7 14
Other tips
While your program gives the correct output, your method doesn’t follow the specs in the assignment. It was supposed to check only one number for perfectness. Only your main program should iterate over numbers to find all perfect numbers up to the max.
You’ve got your condition turned in an unusual way here, which makes it hard for me to read:
for (int test = 1; number >= test; test++) {
Prefer
for (int test = 1; test <= number; test++) {
For building strings piecewise learn to use a StringBuffer or StringBuilder.
Link
Java StringBuilder class on Javapoint Tutorials, with examples.
I have no idea how to phrase the title so feel free to make changes! I am stuck on this program that I have made involving a loop. I want the input to be 1 5 which means the code starts adding from 1 and all the way until 5, the expected output would be 1 + 2 + 3 + 4 + 5 = 15 but my code (see below) would print something like 1 + 2 + 3 + 4 + 5 + = 15. How do I get rid of that unwanted addition symbol?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int start = keyboard.nextInt();
int end = keyboard.nextInt();
double dend = (double)end;
double dstart = (double)start;
double n = (dend - dstart + 1);
double sum = (n/2)*(dend+dstart);
int intsum = (int)sum;
for (int i =start; i <= end; i++) {
System.out.print(i+" + ");
}
System.out.print(" = "+intsum);
}
You could reduce the looping by one, and then print again
for (int i =start; i < end; i++) {
System.out.print(i+" + ");
}
System.out.print(end);
System.out.print(" = "+intsum);
or you could have if logic in your loop
for (int i =start; i <= end; i++) {
System.out.print(i);
if (i != end) System.out.print(" + ");
}
The logic could be something like:
for (int i =start; i <= end; i++)
{
if (i > start)
System.out.print(" + ");
System.out.print(i);
}
The idea is you only print "+" AFTER the first iteration of the loop.
Another option is to use a StringJoiner:
StringJoiner sj = new StringJoiner(" + ");
for (int i =start; i <= end; i++)
{
sj.add( i + "" ); // converts the "i" to a string
}
System.out.print( sj.toString() );
The StringJoiner will add the delimiter for you automatically as required.
As already mentioned by Scary Wombat you can reduce the lopping by one but in your code you are doing string concatenation for each element which not good (because of immutability nature of string in java).
So better to use some mutable string object (either StringBuilder/StringBuffer) and also you can have look at Collectors.joining() (which is introduced in Java8) if you would like implement this using streams.
An alternate solution would be to count the number of iterations and check if it is on it's last iteration. If not, then print a "+".
do
{
System.out.println("Enter either limit, abundant, deficient, perfect, or prime = value:");
condition = scan.next();
String equals = scan.next();
num = scan.next();
value=Integer.parseInt(num);
if (Type.isInteger(condition) || !Type.isInteger(num) || value<0)
System.out.println("Please enter in condition = value format");
else
break;
}while(stop);
System.out.println("N" + "\t" + "Abundant" + " " + "Deficient" + " " + "Perfect" + " " + "Prime");
sigma = 0; //sets sigma=0
n=1;
while (stop)
{
for (f = 1; f <= n/2; f++)
{
if (n % f == 0)
sigma = sigma + f;
}
System.out.print(n + "\t");
if (sigma>n)
acount++;
if (sigma == 1)
p++; //prime counter
if (sigma<n)
dcount++; //deficient counter
if (sigma == n)
pcount++; //perfect counter
System.out.print(acount + " " + "\t" + " " + dcount + "\t" + " " + pcount + "\t" + " " + p); //prints abundant column
System.out.println();
if (condition.equals("limit"))
{
if(n<value)
n++;
else
break;
}
if(condition.equals("abundant"))
{
if(acount<value)
n++;
else
break;
}
if (condition.equals("deficient"))
{
if (dcount<value)
n++;
else
break;
}
if (condition.equals("perfect"))
{
if (pcount<=value)
n++;
else
break;
}
if (condition.equals("prime"))
{
if (p<value)
n++;
else
break;
}
}
}
}
Essentially, the code is supposed to print out 5 columns: n, abundant, deficient, perfect, and prime. And each row will have a column of numbers under it. The user is supposed to type in specifications in a 'condition = value' format. So if they type in limit = 10 then it will print 10 rows. And if they input abundant = 10 then it will continue to print rows until the value of abundant reaches 10. The problem I am encountering is that my program will infinity loop when I input certain values and I am not sure what the cause is. For example, if I input deficient = 2 it will work fine but if I input deficient = 10 then it will start an infinite loop. However, when I input perfect = 10 it will only print out 1 row. Like my title says I am a beginner and I can't figure out what is causing the error. Any suggestions?
Try initializing the value of sigma inside the loop:
while (stop)
{
sigma = 0;
...
}
Since sigma is never reset to zero, it just keeps growing for every number. So you will quickly stop finding deficient numbers or perfect numbers, and everything will be be abundant. That's why the abundant keyword works, but deficient does not.
I need to print the factors of a perfect number. Here's the gist of my main class:
ArrayList<Integer> perfNums = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.print("Enter the upperbound: ");
upperbound = in.nextInt();
for (int i = 1; i <= upperbound; i++) {
if (isPerfect(i)) { //boolean to check if number is a perfect number
perfNums.add(i);
}
}
System.out.println("Perfect numbers between 1 and " + upperbound + " are:");
for (int i = 0; i < perfNums.size(); i++) {
System.out.print(perfNums.get(i) + " = ");
printFactor((int)perfNums.get(i));
System.out.println();
}
Here's the printFactor class.
private static void printFactor(int number){
int factor = 1;
while(factor < number){
if (number%factor == 0) System.out.print(factor+ " + ");
//I don't know how to print the + sign otherwise.
factor++;
}
}
And here's a sample output:
Enter the upperbound: 10000
Perfect numbers between 1 and 10000 are:
6 = 1 + 2 + 3 +
28 = 1 + 2 + 4 + 7 + 14 +
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248 +
8128 = 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064 +
I've got the main gist of it but I've struggled with an output issue. Due to the restrictions of my online submission system, my output needs to fit exact specifications.
My question is how do I go about printing all the factors of my perfect number but removing the + sign at the end? (e.g)6 = 1 + 2 + 3
I'm not too sure of many methods to print from a while loop. Would a for-loop be better for my goals? Or are there alternative methods to print the factors of a number?
The least amount of change to address this might be something like this:
private static void printFactor(int number)
System.out.print(1);
int factor = 2;
while (factor<number) {
if (number%factor == 0) System.out.print(" + " + factor);
factor++;
}
}
1 is always a factor, so you can print that before the loop and then prepend + to every subsequent factor.
You should cache the output you want to print into a StringBuilder. Then you are able to remove the last plus sign before you print the whole String. It also has a better performance.
private static void printFactor(int number)
{
StringBuilder output = new StringBuilder();
int factor = 1;
while (factor < number)
{
if (number % factor == 0)
output.append(factor + " + ");
factor++;
}
// remove last plus sign
output.deleteCharAt(output.length() - 1);
// print the whole string
System.out.print(output.toString());
}
Since factor starts from value 1 and number % 1 == 0 will always be true, you might print 1 first and then flip factor and + in System.out.print. Like this:
private static void printFactor(int number) {
if(number > 0) {
System.out.print(1);
}
int factor = 2;
while (factor<number) {
if (number % factor == 0) {
System.out.print(" + " + factor);
}
factor++;
}
}
Not the best solution, but it will do the job.
Try to create a variable String numb and use substring method like this:
String numb ="";
while(factor<number){
if(number%factor == 0)
numb= numb + factor+ " + ";
factor++;
}
System.out.print(numb.substring(0, numb.trim().length()-1));
Just for the sake of using Java 8 :)
private static void printFactor(int number){
System.out.println(IntStream.range(1, number)
.filter(p -> number % p == 0)
.mapToObj(i -> String.valueOf(i))
.collect(Collectors.joining(" + ")));
}
Thanks everyone for the quick response. You all have been a lifesaver, and I managed to pick up some new things to consider when I code in the future.
Anyway, while waiting for a reply I was fiddling with the code and came up with a rather inelegant solution, if anybody's interested. Here's the changes to the main class:
System.out.println("Perfect numbers between 1 and " + upperbound + " are:");
for(int i=0; i<perfNums.size(); i++){
System.out.print(perfNums.get(i) + " = ");
outputString = printFactor2(perfNums.get(i));
if(outStr.endsWith(" + ")) outStr = outStr.substring(0, outStr.length()-3);
//because the submission system would cry foul with even a single extra space
System.out.println(outStr);
}
And here's the changes to the printFactor class:
private static String printFactor2(int number){
String out = "";
int factor = 1;
while(factor<number){
if(number%factor == 0) out += factor + " + ";
factor++;
}
return out;
}
Basically, what I did was append the factors to a string, then removing the trailing + sign using the substring method. On hindsight, I probably should've called the substring method inside the printFactor class instead. Something like return out.substring(0, out.length()-3); perhaps?
Nevertheless, thanks everyone!
I am working on a program where I have to use recursion to calculate the sum of 1/3 + 2/5 + 3/7 + 4/9 + ... + i / (2i + 1). However, I am not sure how to make my program show the term that must be added in order to reach the number enter by the user. For example. If I enter 12, I want to know how many terms of the series [1/3 + 2/5 + 3/7 + 4/9 + ... + i / (2i + 1)] were added to get approximately to the number 12.
What I don't want to get is the sum of inputting 12 which in this case is 5.034490247342584 rather I want to get the term that if I were to sum all numbers up to that term I would get something close to 12.
Any help will be greatly appreciated!
This is my code
import java.util.Scanner;
public class Recursion {
public static void main(String[] args) {
double number;
Scanner input = new Scanner(System.in);
System.out.println("Enter a value= ");
number = input.nextInt();
System.out.println(sum(number) + " is the term that should be added in order to reach " + number);
}
public static double sum(double k) {
if (k == 1)
return 1/3;
else
return ((k/(2*k+1))+ sum(k-1));
}
}
You have this question kind of inside out. If you want to know how many terms you need to add to get to 12, you'll have to reverse your algorithm. Keep adding successive k / (2k + 1) for larger and larger k until you hit your desired target. With your current sum method, you would have to start guessing at starting values of k and perform a sort of "binary search" for an acceptably close solution.
I don't think that this problem should be solved using recursion, but... if you need to implement it on that way, this is a possible solution:
import java.util.Scanner;
public class Recursion {
public static void main(String[] args) {
double number;
Scanner input = new Scanner(System.in);
System.out.println("Enter a value= ");
number = input.nextInt();
double result = 0;
double expectedValue = number;
int k = 0;
while (result < expectedValue) {
k++;
result = sum(k);
}
System.out.println(k
+ " is the term that should be added in order to reach "
+ number + " (" + sum(k) + ")");
}
public static double sum(double k) {
if (k == 1)
return 1 / 3;
else
return ((k / (2 * k + 1)) + sum(k - 1));
}
}