I have to print prime factor of any number in this format. Ex: 32 = 2*2*2*2*2
Heres my code. It works fine for all except for 32, it gives:2*2*2*2*2*
How to avoid the last *.
Heres my code:
public class PF{
public static void pf(int n) {
for(int i = 2; i< n; i++) {
while(n%i == 0) {
System.out.print(i+ "*");
n = n/i;
}
}
if (n > 2) System.out.print(n);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int n = sc.nextInt();
pf(n);
}
Other option, you can avoid the * when n=i in your while loop
public static void pf(int n) {
for (int i = 2; i < n; i++) {
while (n % i == 0) {
System.out.print(i);
if (n != i) {
System.out.print("*");
}
n = n / i;
}
}
if (n > 2)
System.out.print(n);
}
One option is to store the values in a list and print them together like this:
public static void pf(int n) {
List<String> l = new ArrayList<>();
for (int i = 2; i < n; i++) {
while (n % i == 0) {
l.add(String.valueOf(i));
n = n / i;
}
}
System.out.print(String.join("*", l));
if (n > 2) {
System.out.print("*" + n);
}
}
I did this in two ways.
Type 1
public static void pf(int n) {
for(int i = 2; i< n; i++) {
while(n%i == 0) {
System.out.print(i+ "*");
n = n/i;
System.out.print(i>n ? "\b" : ""); //Backspase and remove unwanted character(*) after print
}
}
if (n > 2) System.out.print(n);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int n = sc.nextInt();
pf(n);
}
Type 2
public static void pf(int n) {
for(int i = 2; i< n; i++) {
while(n%i == 0) {
System.out.print(i+ ((i<n) ? "*" : "")); //Skip the unwanted character(*)
n = n/i;
}
}
if (n > 2) System.out.print(n);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int n = sc.nextInt();
pf(n);
}
You have a formatting problem. It makes sense to separate it from the initial calculation; better to deal with different problems separately.
You can generate a list of prime factors and write a method to print the list in the correct format. For this general problem I tend to treat the list as a head with one item that is not preceded by the separator and a tail with all the other entries, each of which is preceded by the separator, your '*' or perhaps a comma in the more common case. Rather than suppressing the separator after the last entry in the list, think of it as suppressing the separator before the first entry. It is easier to identify the first element in a list than the last.
My code is not strict Java, but gives you the general idea.
void printSeparatedList(factorList) {
char separator = '*';
bool firstEntry = true;
for (int factor : factorList) {
if (firstEntry) {
firstEntry = false;
} else {
System.out.print(separator);
}
System.out.print(factor);
}
} // End printSeparatedList
Related
How can I do something like this? I need to create a Fibonacci class with one next () method returning the next Fibonacci string value.
Subsequent calls should return: 0, 1, 1, 2, 3, 5, 8, etc.
The program takes an integer from the user and returns the specified number of string values. Calculations should be made using arrays.
public class Fibonacci {
final long[][] A = {{1, 1}, {1, 0}};
public static void main(String[] args) {
System.out.print("Enter the n th word of the sequence: ");
long n = initialStatement(readValue());
Fibonacci f = new Fibonacci();
for (int i = 0; i < n; i++) {
long[][] b = f.next();
System.out.print(b[0][1]);
}
}
public static long readValue() {
Scanner scanner = new Scanner(System.in);
return scanner.nextLong();
}
public static long initialStatement(long n) {
do {
if (n == 0 || n == 1) {
return n;
} else if (n < 0) {
System.out.print("Wrong value, please enter correct value: ");
n = Fibonacci.readValue();
}
} while (n < 0);
return n;
}
public long[][] next() {
long[][] a =new long[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
a[i][j] += a[i][j] * A[j][i];
}
}
return a ;
}
}
Your matrix is confusing.
Here is a simple alteration of your code with two int instead of matrix.
Test it and let me know.
public class Fibonacci {
long i = -1; // clone of the loop counter i
long fibo1 = 1;
long fibo2 = 1;
public void main(String[] args) {
System.out.print("Enter the n th word of the sequence: ");
long n = initialStatement(readValue());
Fibonacci f = new Fibonacci();
for (int i = 0; i < n; i++) {
System.out.print(f.next());
}
}
public static long readValue() {
Scanner scanner = new Scanner(System.in);
return scanner.nextLong();
}
public static long initialStatement(long n) {
do {
if (n == 0 || n == 1) {
return 1; // fibo(0) == fibo(1) == 1
} else if (n < 0) {
System.out.print("Wrong value, please enter correct value: ");
n = Fibonacci.readValue();
}
} while (n < 0);
return n;
}
public String next() {
i++; // simulation of loop i because it is not a param of next()
if(i >= 2) {
long aux = fibo1 + fibo2;
fibo1 = fibo2;
fibo2 = aux;
}
return ""+ fibo2;
}
}
Fibonacci is a sequence that can be described by:
fibo(0) = 0
fibo(1) = 1
fibo(n) = fibo(n - 1) + fibo(n - 2)
In code, the most simple implementation does not use matrices. You can do something like this in your class:
private int a = 0;
private int b = 0;
public void next() {
// Special case: Return 0 as first number in the sequence.
if(a == 0 && b == 0) {
b = 1;
return 0;
}
// Return the sum of the last two numbers, and store the new last two numbers in a and b.
int result = a + b;
a = b;
b = result;
return result;
}
That will return the Fibonacci sequence starting at 0.
in java what i am trying to do is have a user input a value greater than 0 and with that number they input list that amount of prime numbers starting from 2
so if the user inputs "3" the program will display 2,3,5
if the user inputs "5" the program will display 2,3,5,7,11
and so on
the problem is I cant figure out how to have the user input do this correctly, i either end up with the numbers repeating however many times or the list ending at the user input, any help would be apreciated
import java.util.Scanner;
public class Primes
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
int n = console.nextInt();
if(n<=0)
{
return;
}
else
{
for(int i=2; i < 100; i++)
{
boolean isPrime = true;
for(int j=2; j < i; j++)
{
if(i%j == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
{
System.out.println(i);
}
}
}
}
}
Keep a count of how many primes have been found by changing your for loop to stop when you've found enough primes and performing primesFound++ when a prime is found:
for (int i = 2, primesFound = 0; primesFound < n; i++)
{
boolean isPrime = true;
for (int j = 2; j < i; j++)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
System.out.println(i);
primesFound++;
}
}
I rather have code that is refactored, each method is doing one thing, it makes it much easier to read, debug and maintain.
All we need to do is separate the logic that checks if a number is prime from the logic that goes over the numbers until n prime numbers are found:
public static void main(String[] args) {
printNPrimes(5);
}
static private boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
static private void printNPrimes(int n) {
int i = 2;
while (n > 0) {
if (isPrime(i)) {
System.out.println(i + " is Prime");
n--;
}
i++;
}
}
//prime
int i,j;
Set<Integer> primeNums = new HashSet<>();
Set<Integer> notPrimeNums = new HashSet<>();
Stack<Integer> stack = new Stack<>();
for(i=1; i<fiboList.size(); i++) {
for(j=i+1; j<fiboList.size(); j++) {
if( i % j == 0 ) {
notPrimeNums.add(fiboList.get(i));
}else {
primeNums.add(fiboList.get(i));
}
}
}
stack.addAll(primeNums);
Collections.sort(stack);
System.out.println("Prime numbers:"+" "+stack);
}
I have to write a program that takes a number from the user and then displays the prime factors of the number. This is the program I have so far:
public static void main(String[] args) {
int a = getInt("Give a number: ");
int i = 0;
System.out.println("Your prime factors are: " + primeFactorization(a, i));
}
public static int getInt(String prompt) {
int input;
System.out.print(prompt);
input = console.nextInt();
return input;
}
public static int primeFactorization(int a, int i) {
for (i = 2; i <= a ; i++) {
while (a % i == 0) {
a /= i;
}
}
return i;
}
}
I can't figure out how to get it to print out the list of numbers. Any help is appreciated.
You should return a List<Integer> not a single int, and there is no point in i being an argument. A correct method is
public static List<Integer> primeFactorization(int a) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 2; i <= a ; i++) {
while (a % i == 0) {
list.add(i);
a /= i;
}
}
return list;
}
While #Paul Boddington's answer is better in most cases (i.e. if you are using the values afterwards), for a simple program like yours, you could add all of the factors to a string and return the string. For example:
public static String primeFactorization(int a) {
String factors = "";
for (int i = 2; i <= a ; i++) {
while (a % i == 0) {
factors += i + " ";
a /= i;
}
}
return factors;
}
The code is supposed to write a Java program that reads from the standard input a list of positive integers and determines if any of them can be written as the sum of a subset of the other input integers. Hints: Searching for subsets of integers that add up to a certain value is best done recursively. However, avoid generating all subsets. When you search for a subset with sum x, input integers larger than x do not have to be considered. If y≤x is one of the other input integers, the search for subsets summing up to x can be divided into searching among subsets that include y and those that don't.
import java.util.Scanner;
import java.util.Arrays;
public class jodiejo {
public static int[] integers = new int[1000];
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = 0;
integers = new int[1000];
while (scan.hasNextInt()) {
integers[n] = scan.nextInt();
n++;
}
for (int i = 0; i < n; i++) {
searchSum(integers[i], i);
}
System.out.print("NO");
Arrays.sort(integers, 0, n);
}
public static void searchSum(int number, int position) {
for (int i = position - 1; i >= 0; i--) {
if (number - integers[i] == 0) {
System.out.print("YES");
System.exit(0);
} else if (number - integers[i] > 0) {
searchSum(number - integers[i], i);
} else if (number - integers[i] < 0) {
return
}
}
}
}
You need a semicolon after that last return, i.e:
public static void searchSum(int number, int position) {
for (int i = position - 1; i >= 0; i--) {
if (number - integers[i] == 0) {
System.out.print("YES");
System.exit(0);
} else if (number - integers[i] > 0) {
searchSum(number - integers[i], i);
} else if (number - integers[i] < 0) {
return;
}
}
}
Your problem is here, you don't have semicolon after return statement:
else if(number - integers[i] < 0)
{
return //No Semicolon
}
in line:49
instead of return , return; - missing ;
I think the error must be here:
else if(number - integers[i] < 0)
{
return //this is the problem
}
}
So just put a semi colon ; after return like return;
And why are you initializing your integers array second time inside the main method:
integers = new int[1000];
It is redundant.
import java.util.Scanner;
import java.util.Arrays;
public class jodiejo
{
public static int[] integers = new int[1000];
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int n = 0;
integers = new int[1000];
while (scan.hasNextInt())
{
integers[n] = scan.nextInt();
n++;
}
for (int i = 0; i < n; i++)
{
searchSum(integers[i], i);
}
System.out.print("NO");
Arrays.sort(integers, 0, n);
}
public static void searchSum(int number,
int position)
{
for (int i = position - 1; i >= 0; i--)
{
if (number - integers[i] == 0)
{
System.out.print("YES");
System.exit(0);
}
else if (number - integers[i] > 0)
{
searchSum(number - integers[i], i);
}
else if (number - integers[i] < 0)
{
return;
}
}
}
}
the following s the code to
Find the number of occurrences of a given digit in a number.wat shall i do in order to Find the digit that occurs most in a given number.(should i create array and save those values and then compare)
can anyone please help me ..
import java.util.*;
public class NumOccurenceDigit
{
public static void main(String[] args)
{
Scanner s= new Scanner(System.in);
System.out.println("Enter a Valid Digit.(contaioning only numerals)");
int number = s.nextInt();
String numberStr = Integer.toString(number);
int numLength = numberStr.length();
System.out.println("Enter numer to find its occurence");
int noToFindOccurance = s.nextInt();
String noToFindOccuranceStr = Integer.toString(noToFindOccurance);
char noToFindOccuranceChar=noToFindOccuranceStr.charAt(0);
int count = 0;
char firstChar = 0;
int i = numLength-1;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
static void recFunNumOccurenceDigit(char firstChar,int count,int i,char noToFindOccuranceChar,String numberStr)
{
if(i >= 0)
{
firstChar = numberStr.charAt(i);
if(firstChar == noToFindOccuranceChar)
//if(a.compareTo(noToFindOccuranceStr) == 0)
{
count++;
}
i--;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
else
{
System.out.println("The number of occurance of the "+noToFindOccuranceChar+" is :"+count);
System.exit(0);
}
}
}
/*
* Enter a Valid Digit.(contaioning only numerals)
456456
Enter numer to find its occurence
4
The number of occurance of the 4 is :2*/
O(n)
keep int digits[] = new int[10];
every time encounter with digit i increase value of digits[i]++
the return the max of digits array and its index. that's all.
Here is my Java code:
public static int countMaxOccurence(String s) {
int digits[] = new int[10];
for (int i = 0; i < s.length(); i++) {
int j = s.charAt(i) - 48;
digits[j]++;
}
int digit = 0;
int count = digits[0];
for (int i = 1; i < 10; i++) {
if (digits[i] > count) {
count = digits[i];
digit = i;
}
}
System.out.println("digit = " + digit + " count= " + count);
return digit;
}
and here are some tests
System.out.println(countMaxOccurence("12365444433212"));
System.out.println(countMaxOccurence("1111111"));
declare a count[] array
and change your find function to something like
//for (i = 1 to n)
{
count[numberStr.charAt(i)]++;
}
then find the largest item in count[]
public class Demo{
public static void main(String[] args) {
System.out.println("Result: " + maxOccurDigit(327277));
}
public static int maxOccurDigit(int n) {
int maxCount = 0;
int maxNumber = 0;
if (n < 0) {
n = n * (-1);
}
for (int i = 0; i <= 9; i++) {
int num = n;
int count = 0;
while (num > 0) {
if (num % 10 == i) {
count++;
}
num = num / 10;
}
if (count > maxCount) {
maxCount = count;
maxNumber = i;
} else if (count == maxCount) {
maxNumber = -1;
}
}
return maxNumber;
}}
The above code returns the digit that occur the most in a given number. If there is no such digit, it will return -1 (i.e.if there are 2 or more digits that occurs same number of times then -1 is returned. For e.g. if 323277 is passed then result is -1). Also if a number with single digit is passed then number itself is returned back. For e.g. if number 5 is passed then result is 5.