Archive

Posts Tagged ‘java code’

Program to find practical numbers


In number theory, a practical number or panarithmic number is a positive integer n such that all smaller positive integers can be represented as sums of distinct divisors of n. For example, 12 is a practical number because all the numbers from 1 to 11 can be expressed as sums of its divisors 1, 2, 3, 4, and 6: as well as these divisors themselves, we have 5=3+2, 7=6+1, 8=6+2, 9=6+3, 10=6+3+1, and 11=6+3+2.

The sequence of practical numbers

1, 2, 4, 6, 8, 12, 16, 18, 20, 24, 28, 30, 32, 36, 40, 42, 48, 54, ….

Here is the Java code to find practical numbers in between given sequence.

/**
*
* @author Vasanth Raja Chittampally
*/
public class PracticalNumbers {
public int[] getPracticalNumbers(int from, int to) {
int a[]=new int[to-from];
int indx=0;
out:for (int i = from; i<=to;i++) {
int sum=0;
for(int j=1;j<=i/2;j++) {
if(i%j==0) {
if(sum<j-1)
continue out;
sum+=j;
}
}
if(sum>=i-1) {
a[indx++]=i;
}
}
int count=0;
for (int i = 0; i < a.length; i++) {
if(a[i]!=0)
count++;
}
int ans[]=new int[count];
for (int i = 0; i <count; i++) {
ans[i]=a[i];
}
return ans;

}

//  You could use this sample code to test function
//  Following main fucntion contains 3 representative test cases
public static void main(String[] arg) {
PracticalNumbers pn = new PracticalNumbers();
//1st test case
int[] res = pn.getPracticalNumbers(1, 20);
for (int i = 0; i < res.length; i++)
System.out.print(res[i] + " ");
System.out.println();
//2nd test case
int[] res2 = pn.getPracticalNumbers(8000, 8200);
for (int i = 0; i < res2.length; i++)
System.out.print(res2[i] + " ");
System.out.println();

//3rd test case
int[] res3 = pn.getPracticalNumbers(1000, 1120);
for (int i = 0; i < res3.length; i++)
System.out.print(res3[i] + " ");
System.out.println();
}
}

Here is the online ide where you can see the output

I feel the above program is self explanatory. If you have any doubts at any line please leave a comment. I’ll clarify your doubts. Thank you. I always welcome your comments or suggestions.

Advertisements

What is the largest prime factor of the number 600851475143 ?


The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

Here is the Java code using BigInteger to represent the given number.

package projecteuler;
import java.math.BigInteger;
/**
*
* @author Vasanth Raja Chittampally
*/
public class ProjectEuler {
public static void main(String[] args)
{
BigInteger bi=new BigInteger("600851475143");
int div=7;
while(bi.compareTo(new BigInteger("1"))!=0) {
while(bi.mod(new BigInteger(div+"")).compareTo(new BigInteger("0"))==0) {
bi=bi.divide(new BigInteger(div+""));
}
div+=2;
}
System.out.println(""+div);
}
}

I tested the above code using Java. The answer it gives is 6857. It does take less than 1sec of execution time.