Converting a void Algorithm to an int [] - java

So I have a program that will find the prime factorization of a number.
public static void primeFactors(int number){
int i=2;
while(number>1){
if (number%i==0){
System.out.println(i);
number/=i ;
}else{
i++;
if(isPrime(i)==true){
System.out.println(i);
number/=i;
}else{
i++;
}}}}
But the thing is I want it to return as an Array. And It has to be able to take a large number and run within 5 seconds. So I converted the working algorithm to this:
public static int[] primeFactors2(int number){
int[] arrayINT =new int[10];
int i = 2;
int index=0;
while(i<=number/2){
if(number %i==0 && isPrime(i)){
arrayINT[index]=i;
index++;
}
i++;
}
return arrayINT;
}}
And this doesn't return the right result, and isn't efficient speed wise. What the heck am I doing wrong!
And here is isPrime():
public static boolean isPrime(int number){
if (number<2){
return false;
}
if (number==2){
return true;
}
if (number%2==0){
return false;
}
int ceiling=number;
for(int i=3;number>i&&ceiling>i;i+=2){
if(number%i==0){
return false;
}
ceiling=number/i;
} return true;
}

I have modified the code a bit to accommodate your requirement. Please take a look.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
--
public static void main(String[] args) {
primeFactors(630);
System.out.println(Arrays.toString(primeFactors2(630)));
}
public static void primeFactors(int number) {
int i = 2;
int init = number;
while(i<=init/2){
if(number %i==0 && isPrime(i)){
System.out.println(i);
number/=i;
i--;
}
i++;
}
}
public static Integer[] primeFactors2(int number) {
List<Integer> list = new ArrayList<>();
int i = 2;
int init = number;
while(i<=init/2){
if(number %i==0 && isPrime(i)){
list.add(i);
number/=i;
i--;
}
i++;
}
return list.toArray(new Integer[list.size()]);
}
public static boolean isPrime(int number) {
if (number < 2) {
return false;
}
if (number == 2) {
return true;
}
if (number % 2 == 0) {
return false;
}
int ceiling = number;
for (int i = 3; number > i && ceiling > i; i += 2) {
if (number % i == 0) {
return false;
}
ceiling = number / i;
}
return true;
}

Related

Im receiving a String index out of range question for a java program i wrote for my assignment

I would like to apologise in advance if im doing something wrong with the code formatting because this is my second time posting here
I have a java assignment due in a couple of days in which the user enters a string and only the integers are collected from it and placed in the array intArray
Now i think i got the logic right in the code below but when i run it in the main, it asks for the string and the boolean, when i enter both it gives me the error
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 115"
This is what i entered for example
"Enter a string and true if you want to skip errors or false if you want to skip errors
sdak23
false"
this is my main:
import java.util.Scanner;
public class MainStringToIntArray {
public static void main(String[] args) {
Scanner intut = new Scanner(System.in);
Scanner input = new Scanner(System.in);
StringToIntArray s1 = new StringToIntArray();
System.out.println("Enter a string and true if you want to skip errors or false if you want to skip errors");
s1.scanStringToIntArray(intut.next(), input.nextBoolean());
}
}
import java.util.Arrays;
import java.util.Scanner;
public class StringToIntArray {
private int[] intArray = new int[10];
public StringToIntArray() {
Arrays.fill(intArray, Integer.MIN_VALUE);
}
public int indexOf(int intToFind) {
int b = 0;
for (int a = 0; a < intArray.length; a++) {
if (intArray[a] == intToFind) {
b = intArray[a];
}
else {
b = -1;
}
}
return b;
}
public int indexOf(String intToFind) {
int b = 0;
for (int a = 0; a < intArray.length; a++) {
if (intArray[a] == Integer.parseInt(intToFind)) {
b = intArray[a];
}
else {
b = -1;
}
}
return b;
}
public boolean contains(int intToFind) {
int a = indexOf(intToFind);
if (a > 0) {
return true;
}
else {
return false;
}
}
public boolean contains(String intToFind) {
int a = indexOf(intToFind);
if (a > 0) {
return true;
}
else {
return false;
}
}
public int get(int index) {
if(index < 0 && index > 10) {
return Integer.MIN_VALUE;
}
else {
return intArray[index];
}
}
public boolean scanStringToIntArray(String s, Boolean skipErrors) {
Boolean result = null;
Scanner input = new Scanner(s);
int l = s.length();
if ((skipErrors)) {
String discard = null;
for (int a = 0; a < l; a++) {
for (int z = 0; z < l; z++) {
if (input.hasNextInt(s.charAt(z))) {
intArray[a] = s.charAt(z);
System.out.println(a);
result = true;
}
else {
discard = discard + s.charAt(z);
}
}
}
}
else {
for (int v = 0; v < l; v++) {
for (int p = 0; p < l; p++) {
if ((input.hasNextInt(s.charAt(p)))) {
intArray[v] = s.charAt(p);
System.out.println(v);
}
else {
System.out.println(v);
result = false;
}
}
}
}
return result;
}
}
The issue is in the get method. It is logically impossible for the index to be both less than 0 and greater than 10; you probably want to use the logical or operator (||). Also, the maximum index of the array is actually 9, as arrays are zero indexed.
public int get(int index) {
if(index < 0 || index > 9) {
return Integer.MIN_VALUE;
}
else {
return intArray[index];
}
}
There are other logical errors in your code as well. All your indexOf methods should be returning the index where the element was first found instead of the element itself and your else branch is always resetting it to -1 each time it is not found.

Trying to find palindrome number

I am trying to find palindrome no but every time it is showing false for every no even for 121
please Help....
public boolean isPalindrome(int x) {
if(x<0 || x%10==0){
return false;
}
int rev = 0;
while(x!=0){
rev=(rev*10)+(x%10);
x/=10;
}
if(x==rev){
return true;
}
else{
return false;
}
}
enter image description here
As an option, you may create something like this:
public boolean isPalindrome(int x) {
StringBuilder sb = new StringBuilder();
sb.append(x);
return sb.toString().equals(sb.reverse().toString());
}
Because after your while loop ends, x will be 0, you have to act on a copy instead
public boolean isPalindrome(int x) {
int num = x;
if(x<0 || x%10==0){
return false;
}
int rev = 0;
while(x!=0){
rev=(rev*10)+(x%10);
x/=10;
}
if(num==rev){
return true;
}
else{
return false;
}
}
All you need to do is build the new number as you reduce the original. Then compare the two.
for (int i : new int[]{121,12321, 123,34543,20012}) {
System.out.printf("%6d - %s%n", i, isPalindrome(i));
}
public static boolean isPalindrome(int numb) {
int n = 0;
for (int b = numb; b > 0;) {
n *= 10;
n += b%10;
b/=10;
}
return n == numb;
}
Prints
121 - true
12321 - true
123 - false
34543 - true
20012 - false
Hope this is useful:
public static boolean palindrome(int n) {
int nPalindrome = 0;
int nCopy = n;
while (n != 0) {
nPalindrome = nPalindrome *10 + n % 10;
n = n / 10;
}
if (nCopy == nPalindrom) {
return true;
} else {
return false;
}
}
You function can be as simple as below
public static void main(String args[]){
int r,sum=0;
int n=454;//It is the number variable to be checked for palindrome
if(isPalindrome(n)) {
System.out.println("palindrome number ");
} else {
System.out.println("not palindrome number ");
}
}
public boolean isPalindrome(int n) {
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
return n==sum;
}

I'm trying to perform integer division on numbers greater than size of any data type available

As far big numbers are concerned, i know there is a class available in java BigInteger, but i have a constraint that i can't use this and i have to perform division without using library.
This is what i have tried so far, but got memory leakage issues and not getting any answer
private Integer getDivisionResult(ArrayList<Integer> first, ArrayList<Integer> second) {
int firstLength = first.size();
int secondLength = second.size();
int counter = 0;
if (firstLength < secondLength) {
return counter;
}
do {
int carry = 0, cursor1 = firstLength - 1, cursor2 = secondLength - 1;
for (int i = firstLength - 1; i >= 0; i--, cursor1--, secondLength--) {
int value = 0, from = 0;
from = first.get(cursor1) - carry;
if (from < (cursor2 < 0 ? 0 : second.get(cursor2))) {
if (cursor1 > 0) {
from = 10 + from;
}
carry = 1;
} else {
carry = 0;
}
value = from - (cursor2 < 0 ? 0 : second.get(cursor2));
first.set(i, value);
}
counter++;
}while (isLesserThan(second,first));
return counter;
}
private boolean isLesserThan(ArrayList<Integer> list, ArrayList<Integer> firstList) {
boolean result = true;
if (list.size() < firstList.size()) {
return true;
}
for (int i = 0; i < list.size(); i++) {
if (firstList.get(i) > list.get(i)) {
result = true;
break;
} else if (firstList.get(i) == list.get(i)) {
continue;
} else {
result = false;
break;
}
}
return result;
}
I'm calling getDivisionResult inside this method, after passing certain error cases:
/**
* #param numOne
* #param numTwo
* #return sign : true (negative) , false (positive)
*/
public Result getResult(String numOne, String numTwo) {
Result result = new Result();
int res = 0;
boolean sign = false;
ArrayList<Integer> firstNum;
ArrayList<Integer> secondNum;
if (isNegative(numOne)) {
firstNum = getArray(numOne.substring(1));
if (isNegative(numTwo)) {
sign = false;
secondNum = getArray(numTwo.substring(1));
} else {
secondNum = getArray(numTwo);
sign = true;
}
} else {
firstNum = getArray(numOne);
if (isNegative(numTwo)) {
sign = true;
secondNum = getArray(numTwo.substring(1));
} else {
secondNum = getArray(numTwo);
}
}
if (isNull(secondNum)) {
result.setSign("Division by 0 is not permissable");
result.setValue(res);
return result;
} else {
if (isNull(firstNum)) {
result.setSign("");
result.setValue(res);
return result;
}
firstNum = getNumberWithoutZeroes(firstNum);
secondNum = getNumberWithoutZeroes(secondNum);
res = getDivisionResult(firstNum, secondNum);
if (sign) {
result.setSign("-");
} else {
result.setSign("");
}
result.setValue(res);
}
return result;
}
private ArrayList<Integer> getNumberWithoutZeroes(ArrayList<Integer> num) {
ArrayList<Integer> list = new ArrayList<>();
for (Integer x : num) {
if (x == 0) {
continue;
} else {
list.add(x);
}
}
return list;
}
private boolean isNegative(String num) {
boolean result = false;
if (num.startsWith("-")) {
result = true;
}
return result;
}
private boolean isNull(ArrayList<Integer> num) {
boolean result = true;
for (Integer x : num) {
if (x > 0) {
result = false;
}
}
return result;
}
private ArrayList<Integer> getArray(String num) {
ArrayList<Integer> list = new ArrayList<>();
char[] arr = num.toCharArray();
for (int i = 0; i < num.length(); i++) {
list.add(Integer.valueOf(arr[i]));
}
return list;
}
if someone can help me to give a better solution to my problem, I would be grateful
I've made the solution to my own problem, but the problem now is its processing speed.

Max heap and Min heap implementation for median Java

I have to create an ADT to read a number of data and calculate the median of those data. The ADT consist in a MIN and a MAX heap.
The MinHeap class takes the numbers greaters or equal than the median.
public class MinHeap {
public double[] data;
public int Size;
public MinHeap(int size) {
data = new double[size];
Size = 0;
}
public double getMinimum(){
return this.data[0];
}
public boolean isEmpty() {
return (Size == 0);
}
private int getParentIndex(int nodeIndex) {
return (nodeIndex - 1) / 2;
}
public void insertu(double value) throws Exception {
if (Size == data.length)
throw new Exception("Heap's underlying storage is overflow");
else {
Size++;
data[Size - 1] = value;
siftUp(Size - 1);
}
}
public void siftUp(int nodeIndex) {
int parentIndex;
double tmp;
if (nodeIndex != 0) {
parentIndex = getParentIndex(nodeIndex);
if (data[parentIndex] > data[nodeIndex]) {
tmp = data[parentIndex];
data[parentIndex] = data[nodeIndex];
data[nodeIndex] = tmp;
siftUp(parentIndex);
}
}
}
}`
The MaxHeapclass takes the numbers that are less or equal than the median.
public class MaxHeap{
public double [] _Heap;
public int _size;
public int tam=0;
public MaxHeap (int a){
_Heap = new double[a];
_size = _Heap.length;
for (int i = _Heap.length / 2 ; i >=0 ; i--) {
tam++;
maxHeapify(i);
}
}
private int parent(int pos)
{ return pos / 2; }
private int leftChild(int pos)
{ return (2 * pos); }
private int rightChild(int pos)
{ return (2 * pos) + 1; }
private void swap(int fpos,int spos) {
double tmp;
tmp = _Heap[fpos];
_Heap[fpos] = _Heap[spos];
_Heap[spos] = tmp;
}
private void maxHeapify (int i) {
int l = leftChild(i), r = rightChild(i), largest;
if(l < _size && _Heap[l] > _Heap[i]) {
tam+=2;
largest = l;
}
else largest = i;
if(r < _size && _Heap[r] > _Heap[largest]) {
largest = r;
tam+=2; }
if (largest != i) {
tam++;
swap(i, largest);
maxHeapify (largest); }
}
protected boolean isEmpty() { return _size == 0; }
protected void deleteMax() {
if (_size > 1) {
tam++;
maxHeapify(0);
double max = _Heap[0];
_size--;
swap(0, _size);
maxHeapify(0); }
else _size = 0;
}
protected double extractMax() {
maxHeapify(0);
return _Heap[0];
}
public void insert(double element)
{
_Heap[++tam] = element;
int current = tam;
while(_Heap[current] > _Heap[parent(current)])
{
swap(current,parent(current));
current = parent(current);
}
}
}`
And the ADT:
`import java.util.InputMismatchException;`
`import java.util.Scanner;`
public class ColaPrioridadMediana {
private MinHeap MIN;
private MaxHeap MAX;
private int size;
public ColaPrioridadMediana(int cap) {
if (cap%2==0){
MIN = new MinHeap(cap/2);
MAX = new MaxHeap(cap/2);
}
else{
MIN = new MinHeap((cap+1)/2);
MAX = new MaxHeap((cap+1)/2);
}
size = MAX.counter + MIN.Size;
}
public void insertar(double x) throws Exception{
if (x <= MAX.extractMax()){
if (MAX.counter > MIN.Size){
double d = MAX.extractMax();
MIN.insertu(d);
MAX.insert(x);
}
else{
MAX.insert(x);
}
}
else{
if (MIN.Size > MAX.counter){
double d = MIN.getMinimum();
MAX.insert(d);
MIN.data[0] = x;
MIN.siftUp(1);
}
else{
MIN.insertu(x);
}
}
}
public int getSize(){
return size;
}
public double getMediana() throws Exception{
if(MAX.counter==MIN.Size){return ((MAX.extractMax()+MIN.getMinimum())/2);}
else{
if (MAX.counter<MIN.Size){return MIN.getMinimum();}
else{return MAX.extractMax();}
}
}
public static void main(String[] args) throws NumberFormatException, Exception{
#SuppressWarnings("resource")
Scanner num=new Scanner(System.in);
ColaPrioridadMediana allNumbers=new ColaPrioridadMediana(10);
while(true){
System.out.print("Number:");
try{
String number=num.nextLine();
double d;
if(!number.isEmpty()){
allNumbers.insertar(Double.parseDouble(number));
}else{
d = allNumbers.getMediana();
System.out.println("The result is " + d);
System.out.println(allNumbers.MAX.extractMax());
System.out.println(allNumbers.MIN.getMinimum());
System.out.println(allNumbers.MAX.counter);
System.out.println(allNumbers.MIN.Size);
for (int i=0;i<allNumbers.MAX._Heap.length;i++){
System.out.println(allNumbers.MAX._Heap[i]);
System.out.println(allNumbers.MIN.data[i]);
}
System.exit(0);
}
}
catch(InputMismatchException e){
System.out.println("Not number");
}
}
}
}`
The MinHeap works, but the MaxHeap don't store any numbers, and prints only 0.0. I'm really stuck in here.
In java, using the Java Standard class PriorityQueue to simulate Max-Min heap is not a bad idea. It will reduce coding significantly.
public class MaxMinHeap{
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((x,y)->(y-x));
private void add(int val) {
if (maxHeap.size() == 0) {
maxHeap.add(val);
} else {
int maxTop = maxHeap.peek();
if (val <= maxTop) {
maxHeap.add(val);
} else {
minHeap.add(val);
}
if (maxHeap.size() - minHeap.size() > 1) {
minHeap.add(maxHeap.poll());
} else if (minHeap.size() - maxHeap.size() > 1) {
maxHeap.add(minHeap.poll());
}
}
}
private double findMedian() {
if(maxHeap.size() > minHeap.size()) {
return maxHeap.peek();
}else if(maxHeap.size() == minHeap.size()) {
return ((double) maxHeap.peek() + minHeap.peek()) / 2;
}else {
return minHeap.peek();
}
}
}

fibonacci recursive method with special output

I'm looking to generate a specific output with my fibonacci recursive method. I already have the recursive code. However the output should display the fibonacci number(one per line) and also the ratio of the current and previous fibonacci numbers on each line.
(if user enters 5)
Fib#1=0
Fib#2=1
Fib#3=1; 1/1=1
Fib#4=2; 2/1=2
Fib#5=3; 3/2=1
this is the code i have so far:
if(n == 0)
return "0";
else if(n == 1)
return "1";
else
return FibonacciCalc(n - 1) + FibonacciCalc(n - 2);
How do i make that output? Should i return a String or make a different print method? Thanks
The problem with this recursive function is that it would be very inefficient as it has the calculate the whole range every time. Better to do this in a loop.
int beforeLastNumber = 1;
int lastNumber = 1;
System.out.println("0");
System.out.println("1");
for(int number=2; number<max; number++) {
int nextNumber = beforeLastNumber + lastNumber;
beforeLastNumber = lastNumber;
lastNumber = nextNumber;
System.out.println(nextNumber);
}
The above keeps a running total of where we're at, which avoid recalculating a sum of lots of numbers to get the higher ones.
Try this:
public class fib {
public static int FibonnaciCalc(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return FibonnaciCalc(n - 1) + FibonnaciCalc(n - 2);
}
public static void main(String[] args) {
final List<Integer> fibList = new ArrayList<Integer>();
int limit = 5;
for (int i = 0; i < limit; i++)
fibList.add(FibonnaciCalc(i));
int tmp = 0;
for (int i=0;i<fibList.size();i++) {
tmp=i+1;
if (i <2)
System.out.println("Fib#" + tmp + "=" + fibList.get(i));
else
System.out.println("Fib#" + tmp + "=" + fibList.get(i)+"; "+fibList.get(i) +"/"+fibList.get(i-1)+"="+fibList.get(i)/fibList.get(i-1));
}
}
}
Recursive fibonacci output
class FibonacciContext {
int beforePrevious;
int previous;
public FibonacciContext(int beforePrevious, int previous) {
this.beforePrevious = beforePrevious;
this.previous = previous;
}
public int getBeforePrevious() {
return beforePrevious();
}
public int getPrevious() {
return previous;
}
public int getNext() {
return beforePrevious + previous;
}
public FibonnaciContext getNextContext() {
return new FibonnaciContext(previous, getNext());
}
}
public FibonacciContext outputFibonacciNumbers(int maxIndex) {
// 0 and 1 are 0 and 1 - non recursive termination
if (maxIndex<2) {
System.out.println(maxIndex);
return new FibonnaciContext(0, maxIndex);
}
// output all previous numbers before this one
FibonnaciContext context = outputFibonacciNumbers(maxIndex-1);
// print out this one
System.out.println(context.getNext());
// context passed back to the recursive call
return context.getNextContext();
}
Try this one:
public static void main(String[] args) {
new Main().f(5);
}
private void f(final int i) {
if (i > 2) {
f(i - 1);
System.out.println(String.format("Fib#%1$d=%2$d; %2$d/%3$d=%4$d", i, fib(i-1), fib(i-2), fib(i-1)/fib(i-2)));
} else if (i > 0) {
f(i - 1);
System.out.println(String.format("Fib#%1$d=%2$d", i, fib(i-1)));
}
}
private int fib(final int i) {
if (i == 0) {
return 0;
} else if (i == 1) {
return 1;
} else {
return fib(i - 2) + fib(i - 1);
}
}

Categories