I need to write up factorial up to 23! I can do factorial up to 20! but after that I am lost because the number gets too big. I cannot use BigInteger.
I have to store the 0s from the rightmost digit so example outputs:
10! = 3628800 --> fac=36288, num10 = 2
23! = 2585..976640000 --> fac= 2585..97664, num10 = 4
import java.util.Scanner;
public class Factorial10{
public static void main(String[] args){
long fac; // long: factorial is very large
long pre_fac; // to check overflow
int i, n;
int num10;
Scanner sc = new Scanner(System.in);
System.out.print("n? ");
n = sc.nextInt();
// Start from fac = 0! = 1
for(i= 1, fac= 1L; i<n; i++){
pre_fac = fac;
fac *= i;
// check if overflowed
if(pre_fac != fac /i){
System.out.println("Overflowed at " + i + "! = " + fac);
fac = pre_fac; // roll back to the previous, unoverflowed
break;
}
}
System.out.println((i-1) + "! = " + fac + "(fac = , num10 = )");
}
}
```
Most miss a crucial part of your question:
I have to store the 0s from the rightmost digit
10 has the factors 2 and 5, so you only need to store how often each number between 1 and 23 can be divided by 2 and 5.
For example, with 10:
i 1 2 3 4 5 6 7 8 9 10 SUM
div2 0 1 0 2 0 1 0 3 0 1 8
div5 0 0 0 0 1 0 0 0 0 1 2
As we can see, the minimum of both sums is 2, so 10! should end with 00.
Indeed, 10! is 3628800.
The math behind this is 10! = x * 2^8 * 5^2, for some x that can't be divided by 2 or 5.
An other observation is that the number of 5s increases much slower, so we can skip counting the 2s.
With this knowledge, we can calculate the number of ending 0s by checking how often each number divides 5:
private static int numZerosInFactorial(int n) {
int divBy5 = 0;
for (int i = 1; i <= n; i++) {
for (int j = i; (j % 5) == 0; j /= 5) {
divBy5++;
}
}
return divBy5;
}
(There are are a few small improvements you can do to the above method)
The other question now is: Do you really need the value of n!?
And if yes, with what precision? Is it fine to calculate n! with double now?
Thanks to a comment from Michael, I noticed that we can in fact calculate the factorial without the zeros and then use string concatenation to display the result.
When calculating the factorial without zeroes, we have to basically do the opposite of what we did in numZerosInFactorial, so instead of multiplying with a multiple of 5, we divide by 2:
private static long factorialWithoutZeroes(int n) {
long result = 1;
for (int i = 1; i <= n; i++) {
long div = 1;
int j;
for (j = i; (j % 5) == 0; j /= 5) {
div *= 2;
}
result = result / div * j;
}
return result;
}
The final result would be:
// We have already read n from stdin
long fac = factorialWithoutZeroes(n);
int num10 = numZerosInFactorial(n);
System.out.println(n + "! = " + (fac + "0".repeat(num10)) + " (fac = " + fac + " , num10 = " + num10 + ")");
Indeed, this approach works up to n == 23. And the output format is a good hint that this is the expected approach.
Have you try to use double instead of long. As documentation in Double.Max - it can hold up to 1.7976931348623157e+308
Just implement your own kind of big integer:
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int[] factorial = factorial(n);
for (int i = factorial.length - 1; i >= 0; i--) {
System.out.print(factorial[i]);
}
}
static int[] factorial(int n) {
int[] factorial = { 1 };
for (int i = 1; i <= n; i++) {
factorial = multiply(factorial, i);
}
return factorial;
}
static int[] multiply(int[] multiplicand, int multiplicator) {
int carry = 0;
for (int j = 0; j < multiplicand.length; j++) {
multiplicand[j] = multiplicand[j] * multiplicator + carry;
carry = multiplicand[j] / 10;
multiplicand[j] %= 10;
}
while (carry > 0) {
multiplicand= Arrays.copyOf(multiplicand, multiplicand.length + 1);
multiplicand[multiplicand.length - 1] = carry % 10;
carry /= 10;
}
return multiplicand;
}
}
Try it online!
If you can't use BigInteger, then you could try implementing your own big number library:
How to handle very large numbers in Java without using java.math.BigInteger
You can use the class BigDecimal of java.lang.math
But that can take all your memory.
Is there any replacement of long double in java?
Related
There is a natural number n. You have to find a pair of natural numbers x, y whose sum is n and also have the least energy among other pair having the sum n.
Energy(x) = sum of all digits of x
Total Energy = Energy(x) + Energy(y)
1 <= n <= 10^9
For eg,
n = 10000
A few pairs:
5000 + 5000 -> Energy = 10
1000 + 9000 -> Energy = 10
9999 + 1 -> Energy = 37
2999 + 7001 -> Energy = 37
So possible answers are:
(5000, 5000), (1000, 9000) etc
I have tried the solution noted above so far but it is not an optimized approach
I will loop from 1 to n-1 and and try all pairs and check their sum of digits but it will take too much time for big numbers.
e.g.
n= 50
1,49--> energy 14
2,48--> energy 14
3,47--> energy 14
4,46--> energy 14
5,45--> energy 14
.
.
.
.
10,40-->energy 5
(Edited) After some thought, I arrived at the following solution. Would appreciate if somebody can come up with a better solution
public int sum(int n) {
String s = String.valueOf(n);
if (isNonZeroOnlyOne(n)) {
int num = getNonZeroNo(n);
if (num == 1)
return 10;
return num;
}
return calculateEnergy(s);
}
private int calculateEnergy(String s) {
int sum = 0;
for(int i=0; i<s.length(); i++)
sum += s.charAt(i) - '0';
return sum;
}
private int getNonZeroNo(int n) {
String s = String.valueOf(n);
for(int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if (c != '0')
return c-'0';
}
return '0';
}
private boolean isNonZeroOnlyOne(int n) {
String s = String.valueOf(n);
int count = 0;
for(int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if (c != '0')
count++;
if (count > 1)
return false;
}
return true;
}
It's simple.
if n is of type 10^x then the answer is 10. otherwise answer is the sum of digits of n.
The idea here is to break down the number into a pair containing digits less than that are present in n. if you break down into smaller digits then sum remains the same as the original number.
example for 7= 1-6,2-5,3-4.
for a number like 100, 1000....
digit 1 can't be broken down into further pairs, so we try to make 10 as the sum of digit so that the sum becomes n.
like for 10=5-5,2-8,3-7
100=20-80,40-60
for other numbers, like 123
it can be broken into 100-23, 120-3, 111-12... all will give you sum 6. which is the sum of digits of the original number.
if you try to break down into further pairs like 80-43, 52-71, you will see that the digit sum increases as you broken down to a number containing digits which is higher than those are present in n. like 8 4,5,7 are greater than 3.
The least energy can be derived by a simple formula.
1) Given N > 100, the pair can be N-100 and 100 , and the energy will be same as the energy of N.
eg : N = 500 ; Pair = 400 and 100 ; Energy = 5
2) N >=10 and N <=100 , pair = N-10 and 10
eg : N = 50 ; Pair = 40 and 10 ; Energy = 5
3) N >=2 and N <=10 , pair = N-1 and 1
eg : N = 5 ; Pair = 4 and 1 ; Energy = 5
I spent more than 1 hour on this problem. What should be answer for n = 1? So I think n should be greater than 1. I am assuming n > 1.
So brute-force solution won't work here because n is huge enough. So you need more optimized solution. You need to think think about how many times you have to carry 1 in the sum to make n. It is at most 9 times!
If you have some basic idea with digit-dp(Dynamic Programming) then this problem is easy. Try to place all possible digit on a place of n and take minimum energy among them. This problem is easy when you fully understand digit-dp technique. You can learn it from here and here.
For practice, you can find a lot of problems here (Dynamic programming section).
For your references, I wrote this code just now and it is working properly. Hope you can use this as a reference.
#include <bits/stdc++.h>
using namespace std;
const string INF_STRING = "9999999";
const int INF_INT = 9999999;
pair<string, int> INF = make_pair(INF_STRING, INF_INT);
int nod;
int digits[10];
int num_of_digits(int a) {
int cnt = 0;
while(a) {
digits[cnt] = a % 10;
a = a / 10;
cnt++;
}
return cnt;
}
pair<string, int> dp[10][2][2][2];
pair<string, int> solve(int ind, int carry, bool is1, bool is2) {
if(ind >= nod) {
if(carry != 0 || !is1 || !is2) return INF;
return make_pair("", 0);
}
pair<string, int> &ret = dp[ind][carry][is1][is2];
if(ret.second != -1) return ret;
ret = INF;
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
int s = (i + j + carry);
pair<string, int> cur = INF;
if(s % 10 == digits[ind]) {
cur = solve(ind + 1, s / 10, is1 || (i > 0? 1:0), is2 || (j > 0? 1:0));
}
if((cur.second + i + j) < ret.second) {
ret.second = cur.second + i + j;
ret.first = cur.first + (char)(i + '0');
}
}
}
return ret;
}
int stringToInt(string num) {
stringstream ss;
ss<<num;
int ret;
ss >> ret;
return ret;
}
int main() {
int i, t, cases = 1, j, k, pos;
int n;
scanf("%d", &n);
nod = num_of_digits(n);
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 2; j++) {
dp[i][j][0][0] = make_pair(INF_STRING, -1);
dp[i][j][0][1] = make_pair(INF_STRING, -1);
dp[i][j][1][0] = make_pair(INF_STRING, -1);
dp[i][j][1][1] = make_pair(INF_STRING, -1);
}
}
pair<string, int> res = solve(0, 0, 0, 0);
string num1_str = res.first;
int num1 = stringToInt(num1_str);
int num2 = n - num1;
printf("Minimum Energy: %d\n", res.second);
printf("Num1 = %d, Num2 = %d\n", num1, num2);
return 0;
}
/*
Input:
10000
Output:
Minimum energy: 10
Num1 = 1000, Num2 = 9000
*/
Here is the answer in javascript in simple way.
function calculateEnergy(n) {
let e = 0
while(n > 0) {
e += n % 10
n = Math.floor(n / 10)
}
return e
}
function countMinEnergy(n) {
let minE = n
let i = 1
while(i <= n/2) {
let e = calculateEnergy(i) + calculateEnergy(n - i)
minE = e < minE ? e : minE
i++
}
return minE
}
countMinEnergy(4325)
Here is scala solution
object LeastEnergyPair extends App {
private def getCountOfPair(array: Array[Int],sum: Int): mutable.Set[(Int, Int)] = {
val seen = mutable.Set[Int]()
val out = mutable.Set[(Int,Int)]()
array map { x =>
val target = sum - x
if (seen.contains(target) || target*2 == sum)
out += ((Math.min(x,target),Math.max(x,target)))
else
seen += x
}
println(out)
out
}
private def sum(i:Int): Int = i.toString.toCharArray.map(_.asDigit).sum
def findLeastEnergyPair(a: mutable.Set[(Int,Int)]): (Int,Int) = {
var min = Int.MaxValue
var minPair = (0,0)
a.foreach {
case (i,j) =>
if (sum(i) + sum(j) < min) {
min = sum(i) + sum(j)
minPair = (i,j)
println(s"$min ----- $minPair")
}
}
minPair
}
println(findLeastEnergyPair(getCountOfPair((1 to 10000).toArray, 10000)))
}
The below logic will cover all scenarios
if (N%10 == 0) {
x1= (N/10);
x2 = N-x1
}else{
x1 = N-10;
x2 = 10;
}
This is for the "Mini Max Sum" problem on HackerRank, I can't see why it doesn't have a check mark on all of the test cases. Can someone tell me where my problem lies at. The question is:
Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than 32 bit integer.)
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long[] arr = new long[5];
long total = 0, max = 0, min = 0;
for(int arr_i=0; arr_i < 5; arr_i++){
arr[arr_i] = in.nextLong();
min = arr[0];
total += arr[arr_i];
if (arr[arr_i] > max)
max = arr[arr_i];
if (arr[arr_i] <= min)
min = arr[arr_i];
}
System.out.println((total - max) + " " + (total - min));
}
}
This also worked. Thanks!!
static void miniMaxSum(int[] arr) {
List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
Collections.sort(list);
long x=0, y=0;
for(int j=0;j<(list.size()-1);j++){
x = x + list.get(j);
y = y + list.get(j+1);
}
System.out.println(x +" "+y);
}
The problem are the initial values of both min and max.
min is being reset to the first values inside the loop, so it will probably only work if the first or the last value is the minimum one;
max starts with zero, so if all values are negative, max will stay at zero (instead of one of the input values).
Hints: set min and max on the first iteration (i == 0) or, as suggested, use Integer.MAX_VALUE and Integer.MIN_VALUE respectively as initial value (actually long is not needed for min and max, neither is the array)
This is what worked for me in JavaScript:
var sum = 0;
var arry = [];
function miniMaxSum(arr) {
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr.length; j++) {
if (arr[j] !== arr[i]) {
sum += arr[j];
}
}
arry.push(sum);
sum = 0;
}
var min = Math.min(...arry);
var max = Math.max(...arry);
console.log(min, max);
}
static void miniMaxSum(int[] arr) {
int temp = 0;
for (int i = 0; i < arr.length; i++)
{
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
long minSum = 0;
long maxSum = 0;
for(int i = 1; i< arr.length; i++){
maxSum = maxSum + arr[i];
}
for(int i = 0; i< arr.length-1; i++){
minSum = minSum + arr[i];
}
System.out.print(minSum+ " " +maxSum);
}
Worked for me on Python3!
def miniMaxSum(arr):
total = sum(arr)
low = total - min(arr)
high = total - max(arr)
print(high, low)
return
import math
import os
import random
import re
import sys
def miniMaxSum(arr):
arr.sort()
m = sum(arr)
max_num = m - arr[-1]
min_num = m - arr[0]
print(max_num, min_num)
if __name__ == '__main__':
arr = list(map(int, input().rstrip().split()))
miniMaxSum(arr)
This worked for me.
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
import java.util.stream.LongStream;
public class Solution {
// Complete the miniMaxSum function below.
static void miniMaxSum(int[] arr) {
long[] longs = Arrays.stream(arr).asLongStream().toArray();
Arrays.sort(longs);
long sum = LongStream.of(longs).sum();
long min = sum - longs[4];
long max = sum - longs[0];
System.out.println(min + " " + max);
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int[] arr = new int[5];
String[] arrItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < 5; i++) {
int arrItem = Integer.parseInt(arrItems[i]);
arr[i] = arrItem;
}
miniMaxSum(arr);
scanner.close();
}
}
Here's a hint in the question: minimum and maximum values that can be calculated by summing exactly four of the five integers.
Just sort the array first, assuming the array is not sorted. Take two for loop because we want to keep the complexity up to O(n) i.e. Linear.
from 1st index to n - 1. Assuming index starts from 0. This will give you sum of all the element except the smallest element which will be the largest sum.
from 0th index to n - 2. Assuming index starts from 0. This will give you sum of all the element except the largest element which will be the least sum.
Let's say, Our initial numbers are 1, 2, 3, 4 and 5.
We can calculate the following sums using four of the five integers:
If we sum everything except 1, our sum is 2 + 3 + 4 + 5 =14.
If we sum everything except 2, our sum is 1 + 3 + 4 + 5 =13.
If we sum everything except 3, our sum is 1 + 2 + 4 + 5 =12.
If we sum everything except 4, our sum is 1 + 2 + 3 + 5 =11.
If we sum everything except 5, our sum is 1 + 2 + 3 + 4 =10.
public static void minmaxsum(int[] ar1) {
long a, b, c, d, e;
a = (long) ar1[1] + (long) ar1[2] + (long) ar1[3] + (long) ar1[4];
System.out.println(a);
b = (long) ar1[0] + (long) ar1[2] + (long) ar1[3] + (long) ar1[4];
System.out.println(b);
c = (long) ar1[0] + (long) ar1[1] + (long) ar1[3] + (long) ar1[4];
System.out.println(c);
d = (long) ar1[0] + (long) ar1[1] + (long) ar1[2] + (long) ar1[4];
System.out.println(d);
e = (long) ar1[0] + (long) ar1[1] + (long) ar1[2] + (long) ar1[3];
System.out.println(e);
long[] df = new long[] { a, b, c, d, e };
long max = df[0];
for (int i = 0; i < df.length; i++) {
if (df[i] > max) {
max = df[i];
}
}
long min = df[0];
for (int i = 0; i < df.length; i++) {
if (df[i] < min) {
min = df[i];
}
}
System.out.println(min + " " + max);
}
This answer is in PYTHON language. I am a beginner and any improvements are welcome
n = input().split(" ")
n=list(n)
n1 = list(map(int,n))
n2 = list(map(int,n))
n1.sort()
n1.pop()
min =0
max=0
for i in n1:
min+=i
n2.sort()
n2.reverse()
n2.pop()
for j in n2:
max+=j
print(min, max)
I am trying to get the first primitive root of a prime number:
private static int GetPrime(int factors[], int modul) {
for (int i = 2; i < modul; i++) {
int j = 0;
while (j < factors.length) {
int power = (modul - 1) / factors[j];
long g = (long) Math.pow(i, power);
long mod = g % modul;
if (mod == 1) {
j++;
break;
} else if (j + 1 == factors.length) {
return i;
}
j++;
}
}
return 0;
}
As parameters i have prime factors of number (factors) and prime number (modul). I tried to implement function for finding the first prime root, for some numbers it works, but for other it fails. Forexample it gives the correct answer for 23 which is 5, but for 71 it fails, instead of 7 it gives 3. I can't figure out what is wrong.
Basically formula is n^((modul-1)/factor) % modul, if for one of factors the reminder for each n is 1, then n is not a prime root.
I am stuck here:
System.out.println("Enter the number to be added to these factorial numbers:");
System.out.println("1!/1 + 2!/2 + 3!/3 + "); //factorial ie. 5!/5 = 4 * 3 * 2 * 1
n = scan.nextInt();
while (!exit)
{
if (n <= 2)
{
sum = 1;
exit = true;
}
sum = sum + i - 1;
i = i - 1;
if (i == 2)
{
exit = true;
}
}
//m2 = 1 * 1 + (2 * 2) + (2 * 1) + (3 * 3) + (3 * 2) + (3 * 1) + (n * n -1);
//System.out.println(m2);
Seems n is not changing. So you can move it out of the while loop. You asking for factorial, but I can't find a * here.. Maybe you can try this with for loop:
// say you got n = sth here
int sum = 0;
int factorial = 1;
for(int i = 1; i <= n; i++) {
// so factorial = i!
factorial = factorial * i;
// add i!/i to sum, all the way to n!/n
sum = sum + factorial / i;
}
// sum is the result.
return n;
I assume that your main issue is to implement the factorial function. There are two basic ways to do this:
Iteratively, using a loop:
public static long factorialWhileLoop(int n) {
long result = 1;
while (n > 1) {
result *= n--;
}
return result;
}
Or recursively, which I prefer because it has no assignment:
public static long factorialRecurse(int n) {
return n <= 1 ? 1 : n * factorialRecurse(n - 1);
}
As others have already mentioned, to calculate n!/n just use (n-1)!.
And if you want more performance, use a lookup table:
static final int [] FACTORIALS =
{1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880,
3628800, 39916800, 479001600, 6227020800L, 87178291200L,
1307674368000L, 20922789888000, 355687428096000,
6402373705728000, 121645100408832000, 2432902008176640000,
};
int factorial(int n) {
if (n < 0 || n >= FACTORIALS.length ) throw new Exception();
return FACTORIALS[n];
}
There are not too many factorials that can be represented by a 64 bit integer.
However, if you need larger factorials, there are other specialized methods.
I have got a solution for problem 21 in python and it gives the right answer. I tried out someone else's java code and I get the same answer for a value of 10000 and 100000 but when 1000000 is tried, the solution returned by my code differs from two other solutions returned by java code even though all three solutions returned are same for tested values of 10000 and 1000000 and 50000. Anyone got any ideas?
My Python code
def amicable_pairs(n):
"""returns sum of all amicable pairs under n. See project euler for
definition of an amicable pair"""
div_sum = [0]*n
amicable_pairs_set = [0]*n
for i in range(1, n):
for j in range(i*2, n, i):
div_sum[j] += i
#for i in range(1, n):
# div_sum[i] = sum([j + i/j for j in range(2, int(math.sqrt(i)) + 1) if i % j == 0 and i != i/j])
# div_sum[i] = div_sum[i] + 1
#print div_sum
for j in range(n):
if div_sum[j] < n and div_sum[div_sum[j]] == j and div_sum[j] != j:
amicable_pairs_set[j] = j
amicable_pairs_set[div_sum[j]] = div_sum[j]
return sum(amicable_pairs_set)
Java code 1:
public class AmicableNumbers {
public static void main(String[] args) {
long strTime = System.currentTimeMillis();
int sum_ami = 0;
for (int j = 1; j < 1000000; j++) {
int ad = sum_devisors(j);
if (((sum_devisors(ad)) == j) && (j != ad)) {
sum_ami += j;
}
}
System.out.println(sum_ami);
long endTime = System.currentTimeMillis();
System.out.println("time is " + (endTime - strTime) + " ms");
}
public static int sum_devisors(int number) {
if ((number == 1) || (number == 2)) {
return 1;
}
int sum = 0;
int k = (int) Math.sqrt(number);
for (int i = 2; i < k; i++) {
if (number % i == 0) {
sum += i;
sum += (number / i);
}
}
if (k * k == number) {
sum += k;
}
return (sum + 1);// every number divided by 1
}
}
Java code 2:
import java.util.Scanner;
public class AmicableNumbers {
/**
* #author Pavan Koppolu
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//scan the input
System.out.println("Enter a number, to find out sum of amicable numbers: ");
Scanner scan=new Scanner(System.in);
int input=scan.nextInt();
long before=System.currentTimeMillis();
// getting the result
long result=sumOfAllAmicableNumbersUptoGivenNumber(input);
long after=System.currentTimeMillis();
// prints the result on the console
System.out.println("Sum of all amicable numbers below "+input+" : "+result+" Elasped Time : "+(after-before)+" ms");
}
/*
* calculate the sum of the amicable numbers upto the given number
*/
private static long sumOfAllAmicableNumbersUptoGivenNumber(int input)
{
long sum=0,factorsSum=0,sumOfFactors=0;
for(long j=2;j<input;j++)
{
factorsSum=getFactorsSum(j);
if(j!=factorsSum)
{
sumOfFactors=getFactorsSum(factorsSum);
if(j==sumOfFactors)
sum+=j;
}
else
continue;
}
return sum;
}
/*
* find out the sum of the factors
*/
private static long getFactorsSum(long j)
{
long sum=1;
for(int k=2;k<=Math.sqrt(j);k++)
{
if(j%k==0)
sum+=k+j/k;
}
return sum;
}
}
In fact the solutions returned by all three above differ from each other for an input of 1000000
The point is that there are amicable pairs where one partner is less than 1 million and the other is larger than 1 million, namely
(947835,1125765), (998104,1043096)
The Python code doesn't count them,
for j in range(n):
if div_sum[j] < n and div_sum[div_sum[j]] == j and div_sum[j] != j:
but the Java code counts the smaller members of these pairs. That explains the output of the second Java code, since
25275024 + 947835 + 998104 == 27220963
The output of the first Java code is smaller because it omits the amicable pair
(356408, 399592)
The reason is that
356408 = 596*598
but in the code there is
int k = (int) Math.sqrt(number);
for (int i = 2; i < k; i++) {
thus the divisor sum is miscalculated for all numbers divisible by floor(sqrt(n)) that are not squares (Note that the second Java code miscalculates the divisor sum for all squares).