Archive

Posts Tagged ‘java program’

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 sum of all primes below two millions?


The idea to minimize the amount of time is that, if a number has factors other than 1 and itself must exist between 2 and square root of that number.

The above constraint reduces innumerable number of comparisons and saves a lot of space too.

Here is the code to find the sum of all primes below two millions.

<blockquote>package projecteuler;

/**
*
* @author Vasanth Raja Chittampally
*/
public class ProjectEuler {

public static void main(String[] args) {
long sum=2;
out: for (long i = 3; i &lt; 2000000; i++) {
if(i%2==0)
continue out;
for (int j = 3; j &lt;=Math.sqrt(i); j+=2) {
if(i%j==0) continue out;
}
sum+=i;

}
System.out.println(""+sum);
}</blockquote>