Java - Factorial - java

I am printing the factorial of the first 10 numbers, so it is 0 - 9. The below code works for me. But I am unable to make the loop such that the factorial of 0 is within the loop too. Any advice is appreciated. Thank you.
public class fact {
public static void main(String[] args) {
System.out.println("\n\n(f) Loop to print first 10 factorial numbers");
System.out.println("\nFactorial of 0 is 1");
int fact = 1;
int index = 1;
while (index < 10)
{
fact*=index;
System.out.println("Factorial of " + index + " is " + fact);
index++;
}
}
}

How about adding an if condition in your while loop for index 0
int fact = 1;
int index = 0;
while (index < 10)
{
if(index == 0)
System.out.println("\nFactorial of 0 is 1");
else {
fact*=index;
System.out.println("Factorial of " + index + " is " + fact);
}
index++;
}

The factorial of 0 is a special case, so you are better off printing it outside the loop, just as you are doing now.

For big n numbers find factorial and its digit count .
import java.util.Scanner;
public class N_Faktorial {
public static void main(String [] args)
{
int u=1,A[]=new int[9999999];
Scanner scan =new Scanner(System.in);
System.out.print("n=");
int n=scan.nextInt();
A[1]=1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++) {
A[j]*=i;
}
for(int j=1;j<=n;j++)
{
if(A[j]>9)
{
A[j+1]+=A[j]/10;
A[j]%=10;
}
if(A[u+1]!=0) {
u++;
}
}
}
System.out.print(n+"! digit count:"+u+"\\n Result: \\n");
for(int i=u;i>=1;i--)
{
System.out.print(A[i]);
}
}
}

factorialList(10);
public static int factorialList(int indexMax) {
int fact = 1;
if (indexMax > 0) fact = indexMax * factorialList(indexMax - 1);
System.out.println("Factorial of " + indexMax + " is " + fact);
return fact;
}
Fn calls are less effective than loops but I bet it would be optimized to ~ the same on task of this size.

You can do like this
int fact = 1;
int index = 0;
while (index < 10)
{
fact=(index==0)?1:fact*(index);
System.out.println("Factorial of " + index + " is " + fact);
index++;
}

Related

TwinPrimes on JAVA

Twin primes are a pair of prime numbers that differ by 2. For example, 3 and 5 are twin primes, 5 and
7 are twin primes, and 11 and 13 are twin primes. Write a Java program TwinPrimes.java that prompts
the user to input the search range of twin primes, display all the twin primes (2 pairs per line) within
the range, and print the number of twin primes found. The search range is assumed to be positive and
your program should repeatedly perform the same task until a sentinel value of -1 is entered.
The expected output of your program should be as follows:
Round 1:
Enter the search range: 100
(3,5) (5,7)
(11,13) (17,19)
(29,31) (41,43)
(59,61) (71,73)
Number of twin primes less than or equal to 100 is 8
Round 2:
Enter the search range: 150
(3,5) (5,7)
(11,13) (17,19)
(29,31) (41,43)
(59,61) (71,73)
......(Omitted)
Number of twin primes less than or equal to 200 is 15
Round 4:
Enter the search range: -1
End
I know that I am not complected the code, but I am struggling on how to print the Prime numbers in ( , ) ( , )way and how to calculate the number of twin primes show it at the end.
The below coding is what I had to do:
import java.util.Scanner;
import java.util.Random;
public class TwinPrimes {
public static void main(String[] args) {
int i = 0;
int A, B = 0, D = 0;
int num = 0;
System.out.println("Round" + " " + ++i + ":");
Scanner scn = new Scanner(System.in);
System.out.print("Enter the search range:");
A = scn.nextInt();
{
if (A < 0)
System.out.println("End");
}
for (i = 3; i <= A; i++) {
int counter = 0;
for (num = B; num >= 1; num--) {
{
if (B % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
}
}
System.out.println("(" + i + "," + i + ")" + " " + "(" + i + "," + i + ")");
// sum Number of twin primes to
System.out.println("Number of twin primes less than or equal to " + A + " " + "is" + " ");
return;
}
}
}
package array1;
import java.io.IOException;
import java.util.Scanner;
public class Mainclass {
public static void main(String args[]) throws NumberFormatException, IOException
{
int a,k=0,line=0,count=0;
while(true)
{
System.out.println("Round" + " " + ++k + ":");
Scanner scn = new Scanner(System.in);
System.out.print("Enter the search range:");
a= scn.nextInt();
{
if (a< 0)
{
System.out.println("End");
System.exit(0);
}
}
System.out.println("The Twin Prime Numbers within the given range are : ");
for(int i=2; i<=(a-2); i++)
{
if(isPrime(i) == true && isPrime(i+2) == true)
{
System.out.print("("+i+","+(i+2)+") ");
line++;
if(line==2)
{
System.out.println();
line=0;
}
count++;
}
}
System.out.println();
System.out.println("the number of twin prime numbers less than or equal to"+a+"is"+count);
}
}
static boolean isPrime(int n) //funton for checking prime
{
int count=0;
for(int i=1; i<=n; i++)
{
if(n%i == 0)
count++;
}
if(count == 2)
return true;
else
return false;
}
}
I am struggling on how to print the Prime numbers in ( , ) ( , ) way
You may use String.format. See How to use String.format in Java?
For example, String.format("Found pair (%d,%d)", prime1, prime2);
How to calculate the number of twin primes show it at the end.
Simply keep a counter, say int counter when you're looking for the prime pairs.
import java.util.Scanner;
public class Main {
// Consider writing a helper function to check primality
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
for (int i = 2; i <= Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int max_number = 100;
int counter = 0; // keep a count
for (int i = 2; i+2 < max_number; i++) {
if (isPrime(i) && isPrime(i+2)) {
counter++; // increment counter
String msg = String.format("Found pair (%d,%d)", i, i+2);
System.out.println(msg);
}
}
System.out.println("Total number of pairs is " + counter);
// Total number of pairs is 8
}
}

Java sum of EvenNumbers

It counts up to 5 and sum of 5 even numbers. I did it but it didn't work correctly(Mistake is about calculating the sum).Can you look at it ?
Here the code:
package com.java.ornekler;
public class Main {
public static void main(String[] args) {
int n = 1;
int count = 0;
int sum = 0;
do {
isEven(n);
if (!isEven(n)) {
n++;
continue;
} else {
System.out.println(+n + " is a even number ");
n++;
sum = sum + n;
count++;
if (count == 5) {
System.out.println("Sum is : " +sum);
break;
}
}
}
while (n <= 10);
}
public static boolean isEven(int n) {
if ((n % 2) == 0) {
return true;
} else {
return false;
}
}
}
Output is:
2 is a even number
4 is a even number
6 is a even number
8 is a even number
10 is a even number
Sum is : 35
n++;
sum = sum + n; // here you incremented n then added to sum.
change to
sum = sum + n;
n++;
The reason why your sum is at 35 is because you increment your n one more time before you sum it together. Your total is 30 + numberOfN = 35
Your else statement should look like this
else {
System.out.println(+n + " is a even number ");
sum = sum + n;
n++; // this was above and should be here
count++;
if (count == 5) {
System.out.println("Sum is : " +sum);
break;
}
When you find an odd number, you do this:
System.out.println(+n + " is a even number ");
n++;
sum = sum + n;
So, if n==4, first you bump it up so that n==5. Then you add it to sum, so sum increases by 5, not 4.
So fix this, add to sum before incrementing n.
More generally, instead of jumping up in ones, testing for even-ness, why not start on an even number, and jump up in twos?
And, rather than having a println and a break in an if within the loop, make it an exit condition of the loop, and put the println after the loop.
Along with comments above and you have duplicity statement: n++;.
Put that statement after if{}else{} block.
Revise the code as follows:
do {
isEven(n);
if (!isEven(n)) {
continue;
} else {
System.out.println(+n + " is a even number ");
sum = sum + n;
count++;
if (count == 5) {
System.out.println("Sum is : " +sum);
break;
}
}
n++;
}
while (n <= 10);
Java 8 syntax might be easier to follow using predefined functions for summing and limiting
package test.test;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
public class Snippet {
public static void main(String args[]) {
int sum = IntStream.iterate(1, i -> i + 1).limit(10).filter(isEven()).peek(Snippet::printEvenNumber).sum();
System.out.println("Sum is : " + sum);
}
private static void printEvenNumber(int i) {
System.out.println(i + " is an even number");
}
private static IntPredicate isEven() {
return i -> i % 2 == 0;
}
}

What is causing my infinite loop?

I can't seem to figure out what I did wrong with my code to create an infinite loop. I would really appreciate it if someone could help explain this to me.
import java.util.Scanner;
class LoopMath1 {
public static void main(String[] args) {
Scanner inputScanner;
inputScanner = new Scanner(System.in);
//gets a number from a user and parses the string as an int
System.out.println("Please give me a positive number");
String userNum;
userNum = inputScanner.nextLine();
System.out.println("Your number is " + userNum + ".");
int number = Integer.parseInt(userNum);
printX(number); //function call
//prints 2 to the x power
System.out.print("2^" + number + "=");
int j = 1;
int twoToThe = 2;
while (j < number) {
twoToThe *= 2;
j++;
}
System.out.print(twoToThe);
//determines if the user number is prime
int i = 0;
for (i = 1; 1 < number; i++) {
int nPrime = number;
if (nPrime == 0) {
System.out.println(number + " is not prime.");
break;
} else {
System.out.println(number + " is prime.");
}
}
}
//this is a function to print a certain amount of Xs, depending on the user input
public static void printX(int nTimes) {
final int WIDTH = nTimes;
while (nTimes < WIDTH) {
System.out.print("x");
nTimes += 1;
}
}
}
for (i=1; 1 < number; i++) has a typo. 1 should be i as in for (i=1; i < number; i++)
Replace
for (i=1; 1 < number; i++) {
by
for (i=1; i < number; i++) {
Your incrementor initialized in the first part of your for loop must be tested in the second part preferably and incremented in the third one.

How can I reduce this code to use only one while loop?

Here's my code so far:
public class EvenOdd
{
public static void main(String[]args)
{
System.out.print("Even numbers between 50 and 100: ");
int e = 50;
while (e <= 100) {
System.out.print(" " + e);
e += 2;
}
System.out.print("\nOdd numbers between 50 and 100: ");
int i = 51;
while (i <= 100) {
System.out.print(" " + i);
i += 2;
}
}
}
How can I reduce these two while loops to just one while loop?
Store the numbers in two StringBuilders, one for the odd numbers and the other for the even numbers :
public class EvenOdd
{
public static void main(String[]args)
{
StringBuilder even = new StringBuilder();
StringBuilder odd = new StringBuilder();
int e = 50;
while (e <= 100) {
if (e%2 == 0)
even.append (" " + e);
else
odd.append (" " + e);
e++;
}
System.out.print("Even numbers between 50 and 100: " + even.toString());
System.out.print("\nOdd numbers between 50 and 100: " + odd.toString());
}
}
public static void main(String[]args)
{
StringBuilder evenString = new StringBuilder("Even numbers between 50 and 100: ");
StringBuilder oddString = new StringBuilder("Odd numbers between 50 and 100: ");
int e = 50;
while (e <= 100) {
if((e % 2) == 0)
{
evenString.append(" " + e);
}
else
{
oddString.append(" " + e);
}
e++;
}
System.out.println(evenString);
System.out.println(oddString);
}
Use a two StringBuilders to store the strings you want to display then write them out after your done looping. Each loop do modular division (%) to see if its even or odd. If the remainder is 0 then it's even if it's not then it's odd. Based on which one it is just append it to the appropriate StringBuilder.
Reducing code duplication is often a good thing. The most basic tool that Java provides are methods, so you could extract the behavior of your loop in a method and write an equivalent program:
public class EvenOdd
{
public static void main(String[]args)
{
System.out.print("Even numbers between 50 and 100: ");
printEverySecondNumber(50, 100);
System.out.print("\nOdd numbers between 50 and 100: ");
printEverySecondNumber(51, 100);
}
public static void printEverySecondNumber(int start, int end){
int current = start;
while (current <= end) {
System.out.print(" " + current);
current += 2;
}
}
}
Note that this program behaves just the same: The loop will stil get executed twice, but it is not duplicated in code.
Use lists. They print out nicely.
public class EvenOdd
{
public static void main(String[]args)
{
List<String> even = new ArrayList<String>();
List<String> odd = new ArrayList<String>();
int e = 50;
while (e <= 100) {
if (e%2 == 0)
even.add(String.valueOf(e));
else
odd.add(String.valueOf(e));
e++;
}
System.out.print("Even numbers between 50 and 100: " + even);
System.out.print("\nOdd numbers between 50 and 100: " + odd);
}
}
Here is a solution without storing numbers
public static void main(String[] args) {
int i = 0;
System.out.print("Even numbers between 50 and 100: ");
while (i <= 50) {
if (i == 26) {
System.out.print("\nOdd numbers between 50 and 100: ");
}
if (i <= 25) {
System.out.print (" " + (2 * i + 50));
} else {
System.out.print (" " + (2 * (i - 25) + 49));
}
i++;
}
}
If you are determined to do a single loop
int n = 50;
System.out.print("Even numbers between 50 and 100:");
while(n < 151){
if(n <= 100)
System.out.print(" " + n);
else
System.out.print(" " + (n-50));
if(n != 100)
n = n + 2;
else{
System.out.print("\nOdd numbers between 50 and 100:");
n = n + 1;
}
}
The benefit to this is you aren't building any unnecessary objects or having to manage anything other than n really.
If your goal is to reduce loop iterations
StringBuilder evenString = new StringBuilder();
StringBuilder oddString = new StringBuilder();
int n = 50;
while(n <= 100){
evenString.append(" " + n);
if(n != 100)
oddString = oddString.append(" " + (n + 1));
n = n + 2;
}
System.out.println("Even numbers between 50 and 100:" + evenString);
System.out.print("Odd numbers between 50 and 100:" + oddString);
Something to notice, this cuts your iterations in half over using a single while with if statements.
Just re-start iterations by re-setting the counter:
public class EvenOdd
{
public static void main(String[]args)
{
int e = 0;
while (1) {
if (e==0) {
System.out.print("Even numbers between 50 and 100:");
e = 50;
}
else
if (e==102) {
System.out.print("\nOdd numbers between 50 and 100:");
e = 51;
}
else
if (e==101) {
System.out.print("\n");
break;
}
System.out.print(" " + e);
e += 2;
}
}
}

Errors in Java code

I'm trying to get the highest and lowest number entered by user. I got this. I just new in programming. There are 3 errors.
import java.io.*;
public class HighestToLowest
{
public static void main(String []args)throws IOException{
{
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
double[] input = new double[8];
int index;
int highIndex = 0;
int lowIndex = 0;
double sum = 0;
System.out.println("Enter The Scores Of Judges: ");
for (index = 0; index<8; index++){
System.out.print("Enter The Score" + (index + 1) + ": ");
input[index] = Double.parseDouble(dataIn.readLine());
}
for (index = 1; index < 8; index++)
if(input[highIndex] < input[index])
highIndex = index;
for (index = 1; index < 8; index++)
if (input[lowIndex] > input[index])
lowIndex = index;
for (index = 0; index < 8; index++)
sum = sum + input[index];
try
{
input[index] = Double.parseDouble(dataIn.readLine());
}
catch(IOException e)
{
System.out.println("error");
}
if(sum>index)
{
sum=highIndex;
}
if(sum>=index)
{
index=lowIndex;
}
}
System.out.print("Highest is: + highIndex");
System.out.print("Lowest is: + lowIndex");
System.out.printf("The Contestant Receives a total of %.2f", (sum - highIndex - lowIndex));
}
}
Although you say there are only 3 errors, there seen to be a bit more
public static void main(String []args)throws IOException{ //<- ?
{//<- why two curly brackets?
In for loop
for (index = 0; index < 8; index++){//<- curl bracket missing?
sum = sum + input[index];
try {
input[index] = Double.parseDouble(dataIn.readLine());
} catch(IOException e) {
e.printStackTrace();
}
if(sum>index) {
sum=highIndex;
}
if(sum>=index){
index=lowIndex;
}
} // <- or extra curl bracket?
This line will print Highest is: + highIndex
System.out.print("Highest is: + highIndex");
Any thing in " " is printed as it is.
So change it to
System.out.print("Highest is:" + highIndex);
Same applies for
System.out.print("Lowest is: + lowIndex");
Are you from C programming, this line is correct
System.out.printf("The Contestant Receives a total of %.2f", (sum - highIndex - lowIndex));
In Java it can also be written as
System.out.println("The Contestant Receives a total of " + (sum - highIndex - lowIndex));

Categories