Search code examples
javaperfect-numbers

Reversing an array without using another array


I have been trying this using two arrays, and it was successful but the in-place reversing was bit confusing for me. if you can help, that will be great public class reverseOfAnArray {

int[] reverseCal(int arr[]){
int i,j=0;
for (i=arr.length;i>0;i--,j++){
arr[j]=arr[i-1];
}
return arr;
}
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int size,i=0;
System.out.println("enter the size of your array");
size=scan.nextInt();

int originalArray[]=new int[size];
System.out.println("Enter the elemets in the array");
for (i=0;i<size;i++){
originalArray[i]=scan.nextInt();
}
reverseOfAnArray cal=new reverseOfAnArray();
System.out.println("reverse of the given array is 
\n"+Arrays.toString(cal.reverseCal(originalArray)));
}
}

Solution

  • Your problem is that you are stopping the recursion when you find the first number that is not a divisor of a, so in case of 28, you finish the recursion when comingdivisor reaches 3, and miss most of the divisors of 28 (4, 7 and 14).

    Make a recursive call even if a % comingdivisor != 0:

    class perfectNumber {
      int sum=0;
      Integer perfectNumberCal(int a,int comingdivisor) {
        if (comingdivisor<=a/2) {
          if (a % comingdivisor == 0) {
            sum += comingdivisor;
            System.out.println(sum);
          }
          return perfectNumberCal(a,comingdivisor+1);
        }
        return sum;
      }
    }