I'm trying to generate ten large prime numbers. here is my code. I use small numbers to see if it's working.
public static void primeGenerator(){
BigInteger[] primeList = new BigInteger[10];
BigInteger startLine = new BigInteger("1");
int startPower = 1;
BigInteger endLine = new BigInteger("10");
int endPower = 2;
int j = 0;
for (BigInteger i = startLine.pow(startPower);
i.compareTo(endLine.pow(endPower)) <= 0;
i = i.add(BigInteger.ONE)) {
if(checkPrimeFermat(i) == true && j<10)
primeList[j] = i;
j++;
continue;
}
System.out.print(primeList[3]);
}
the outputs:
primeList[0] = null primeList[1] = 2 primeList[2] = 3 primeList[3] = null
outputs I want to generate:
primeList[0] = 2 primeList[1] = 3 primeList[2] = 5 primeList[3] = 7
when the j comes the 4 code didn't check 5 and stop in here. How can I solve this problem? I tested checkPrimeFermat with junit it's working by the way.
This'll work:
public static void primeGenerator() {
BigInteger[] primeList = new BigInteger[10];
BigInteger startLine = new BigInteger("1");
int startPower = 1;
BigInteger endLine = new BigInteger("10");
int endPower = 2;
int j = 0;
for (BigInteger i = startLine.pow(startPower); i.compareTo(endLine
.pow(endPower)) <= 0; i = i.add(BigInteger.ONE)) {
if (checkPrimeFermat(i) == true && j < 10) {
primeList[j] = i;
j++;
}
}
System.out.print(Arrays.toString(primeList));
}
Related
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I wrote a function:
private static LinearFunction[] aproxFunction(List<Point> list) {
try{
int amountOfClusters = getAmountOfClusters(list);
//System.out.println(amountOfClusters); for debug
LinearFunction[] linear = new LinearFunction[amountOfClusters];
int[][] clusters = new int[amountOfClusters][2]; // 2nd field 0 == r, 1 == g, 2 == b
clusters = getClusters(list, amountOfClusters);
for(int i = 0; i < amountOfClusters; i++) {
List<Point> pointsList = new ArrayList<>(getPointsInCluster(list, clusters[i][0], convertIdToString(clusters[i][1])));
int[][] points = new int[pointsList.size()][3];
for(int j = 0; j < points.length; j++) {
points[j][0] = pointsList.get(j).getX();
points[j][1] = pointsList.get(j).getY();
points[j][2] = pointsList.get(j).getValue();
}
pointsToFile(pointsList, clusters[i][0], convertIdToString(clusters[i][1]), "_points_in_cluster_");
int[][] array = new int[2][2];
array = aprox(removeDuplicates(points));
if((array[1][0] - array[0][0]) == 0) {
linear[i].a = 0;
linear[i].b = 0;
linear[i].flag = true;
linear[i].c = array[0][0];
} else {
linear[i].a = (array[1][1] - array[0][1]) / (array[1][0] - array[0][0]);
linear[i].b = array[1][1] - array[1][0] * linear[i].a;
}
linear[i].cluster = clusters[i][0];
linear[i].id = convertIdToString(clusters[i][1]);
}
return linear;
} catch (Exception e) {
System.out.println("Error - aproxFunction: " + e.getMessage());
}
LinearFunction[] error = new LinearFunction[1];
error[0].a = -1;
return error;
}
and I constantly receive the error messages of either division by null or just null. I can't find the reason for that.
The only division in this function happens here:
linear[i].a = (array[1][1] - array[0][1]) / (array[1][0] - array[0][0]);
but above that you have a check for null division, so how can I still get that error message.
As for the error message null I just don't know what it means. I read that it might be caused by an objects being null but how to find out which and where?
You are initialising an array of LinearFunctions, but you are not initialising each LinearFunction object inside it.
Have you tried this:
private static LinearFunction[] aproxFunction(List<Point> list) {
try{
int amountOfClusters = getAmountOfClusters(list);
//System.out.println(amountOfClusters); for debug
LinearFunction[] linear = new LinearFunction[amountOfClusters];
int[][] clusters = new int[amountOfClusters][2]; // 2nd field 0 == r, 1 == g, 2 == b
clusters = getClusters(list, amountOfClusters);
for(int i = 0; i < amountOfClusters; i++) {
linear[i] = new LinearFunction()
...
I solved this NullPointerException like this:
for(int i = 0; i < amountOfClusters; i++) {
LinearFunction lf = new LinearFunction();
List<Point> pointsList = new ArrayList<>(getPointsInCluster(list, clusters[i][0], convertIdToString(clusters[i][1])));
int[][] points = new int[pointsList.size()][3];
for(int j = 0; j < points.length; j++) {
points[j][0] = pointsList.get(j).getX();
points[j][1] = pointsList.get(j).getY();
points[j][2] = pointsList.get(j).getValue();
}
pointsToFile(pointsList, clusters[i][0], convertIdToString(clusters[i][1]), "_points_in_cluster_");
int[][] array = new int[2][2];
array = aprox(removeDuplicates(points));
if((array[1][0] - array[0][0]) == 0) {
lf.a = 0;
lf.b = 0;
lf.flag = true;
lf.c = array[0][0];
} else {
lf.a = (array[1][1] - array[0][1]) / (array[1][0] - array[0][0]);
lf.b = array[1][1] - array[1][0] * linear[i].a;
}
lf.cluster = clusters[i][0];
lf.id = convertIdToString(clusters[i][1]);
linear[i] = lf;
}
So I created an object of the same class as the array, and only at the end of the loop I point it to an element of the array.
My current code is:
int[] usedRVals = new int[8];
int[] usedCVals = new int[8];
Arrays.fill(usedRVals, 99);
Arrays.fill(usedCVals, 99);
for (int l = 0; l < 8; l++) {
r = 0;
c = 0;
// get new random numbers that aren't the same
while (r == c && !Arrays.asList(usedRVals).contains(r) && !Arrays.asList(usedCVals).contains(c)) {
r = randomNum();
c = randomNum();
}
usedRVals[l] = r;
usedCVals[l] = c;
}
private static int randomNum() {
Random r = new Random();
return r.nextInt(8);
}
I'm attemping to get a new number (between 0 and 7) that hasn't been used before in the same loop, but I'm unable to find the logic error in my code. Any help would be appriciated.
My program displays Pascal's triangle. For enlarging the portion of the triangle that may be calculated and displayed, I've rewritten the code using BigInteger instead of primitive types.
Here's the code:
import java.math.BigInteger;
public class ptrig {
public static void main(String args[]) {
BigInteger no = BigInteger.valueOf(5);
// Creating the array
String doubledim[][] = new String[no.intValue()][];
BigInteger k;
for (k = BigInteger.ZERO; k.compareTo(no) < 0; k.add(BigInteger.ONE)) {
doubledim[k.intValue()] = new String[k.intValue() + BigInteger.ONE.intValue()];
}
// Assigning values
BigInteger i, j, p, n;
BigInteger l = BigInteger.ONE;
for (i = BigInteger.ZERO; i.compareTo(no) < 0; i.add(BigInteger.ONE)) {
for (j = BigInteger.ZERO; j.compareTo(i.add(BigInteger.ONE)) < 0; j.add(BigInteger.ONE)) {
BigInteger m = i.subtract(j);
if (j.compareTo(m) > 0) {
for (p = BigInteger.ZERO; p.compareTo(m) < 0; p = p.add(BigInteger.ONE)) {
n = i.subtract(p);
l = l.multiply(n);
}
doubledim[i.intValue()][j.intValue()] = l.divide(factorial.factmet(m)).toString();
l = BigInteger.ONE;
}
if (m.compareTo(j) > 0) {
for (p = BigInteger.ZERO; p.compareTo(j) < 0; p = p.add(BigInteger.ONE)) {
n = i.add(p.add(BigInteger.ONE)).subtract(j);
l = l.multiply(n);
}
doubledim[i.intValue()][j.intValue()] = l.divide(factorial.factmet(j)).toString();
l = BigInteger.ONE;
}
if (m.compareTo(j) == 0) {
for (p = BigInteger.ZERO; p.compareTo(j) < 0; p = p.add(BigInteger.ONE)) {
n = i.subtract(p);
l = l.multiply(n);
}
doubledim[i.intValue()][j.intValue()] = l.divide(factorial.factmet(j)).toString();
l = BigInteger.ONE;
}
}
}
// Printing
for (i = BigInteger.ZERO; i.compareTo(no) < 0; i.add(BigInteger.ONE)) {
for (j = BigInteger.ZERO; j.compareTo(i.add(BigInteger.ONE)) < 0; j.add(BigInteger.ONE)) {
System.out.print(doubledim[i.intValue()][j.intValue()] + " ");
}
System.out.println();
}
}
}
The problem is it displays nothing. I've read on Stack Overflow I need to convert the array values into strings for that they're displayed, so I did. I've also checked the System.out.println statements - they seem to be fine. The error persisted.
The algorithm itself worked fine on a previous version with primitive types.
What's the error here? I did my best to find an answer on the web, I couldn't. Thanks.
Your for-loops aren't incrementing their indices, and will therefor loop forever.
i.add(BigInteger.ONE) doesn't mutate i, it creates a new BigInteger and returns it. If you want to increment the value of i, you need to write i = i.add(BigInteger.ONE)
This means that when you try to initialize your array, you're entering an infinite loop, where you re-initialize doubledim[0] forever.
e.g.
for (k = BigInteger.ZERO; k.compareTo(no) < 0; k.add(BigInteger.ONE)) {
doubledim[k.intValue()] = new String[k.intValue() + BigInteger.ONE.intValue()];
}
should be
for (k = BigInteger.ZERO; k.compareTo(no) < 0; k = k.add(BigInteger.ONE)) {
doubledim[k.intValue()] = new String[k.intValue() + BigInteger.ONE.intValue()];
}
and you'll need to likewise fix the loops that control the population of data in your arrays, and printing of their data later in your program.
I'm working on a brute force approach to the traveling salesman problem. I have a certain line that produces the ArrayIndexOutOfBounds exception, however all the arrays used there have more than enough space. The particular line of code:
testCity[0][a] = cities[0][(int) cityList[a]];
This is where I initialize testCity:
int[][] testCity = new int[2][CITIES+10];
cities:
public static int[][] cities = new int[2][CITIES+10];
And, finally, cityList:
Object[] cityList = new Integer[CITIES+10];
This is the entire error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at BruteF.permute(BruteF.java:39)
at BruteF.permute(BruteF.java:30)
at BruteF.permute(BruteF.java:30)
at BruteF.permute(BruteF.java:30)
at BruteF.main(BruteF.java:11)
And here is the code:
public class BruteF {
public static final int CITIES = 5;
public static int[][] cities = new int[2][CITIES+10];
public static int[][] bestCity = new int[2][CITIES+10];
public static double bestDistance = 1000;
public static int[][] testCity = new int[2][CITIES+10];
public static Object[] cityList = new Integer[CITIES+10];
public static void main(String[] args)
{
permute(java.util.Arrays.asList(1,2,3,4), 0);
for (int i = 0;i < CITIES;i++)
{
System.out.println(bestCity[0][i] + "," + bestCity[1][i]);
}
}
static void permute(java.util.List<Integer> arr, int k){
cities[0][0] = 1;
cities[1][0] = 1;
cities[0][1] = 2;
cities[1][1] = 5;
cities[0][2] = 3;
cities[1][2] = 2;
cities[0][3] = 4;
cities[1][3] = 3;
int originalX = cities[0][0];
int originalY = cities[1][0];
for(int i = k; i < arr.size(); i++){
java.util.Collections.swap(arr, i, k);
permute(arr, k+1);
java.util.Collections.swap(arr, k, i);
}
if (k == arr.size() -1){
for (int i = 0;i < CITIES;i++)
{
cityList = arr.toArray();
for (int a = 0;a < CITIES;a++)
{
testCity[0][a] = cities[0][(int) cityList[a]];
}
if (distance(testCity,CITIES,originalX, originalY) < bestDistance)
{
bestCity = testCity;
bestDistance = distance(testCity,CITIES, originalX, originalY);
}
}
}
}
static double distance (int[][] cities, int CITIES, int originalX, int originalY)
{
int[][] taken = new int[2][CITIES+1];
int takenCounter = 0;
double distance = 0;
cities[0][CITIES] = cities[0][0];
cities[1][CITIES] = cities[1][0];
for (int i = 0;i <= CITIES;i++)
{
for (int z = 0;z <= CITIES;z++)
{
if (cities[0][i] == taken[0][z] && cities[1][i] == taken[1][z])
{
return CITIES*1000; //possible error here
}
else {
taken[0][takenCounter] = cities[0][i];
taken[1][takenCounter] = cities[1][i];
}
}
if (cities[0][0] != originalX && cities[1][0] != originalY)
{
return CITIES*1000; //POSSIBLE BUG HERE
}
distance = distance + Math.sqrt(Math.pow(cities[0][i+1]-cities[0][i],2) + Math.pow(cities[1][i+1]-cities[1][i],2));
}
return distance;
}
}
Why is this happenening? What can I do to fix it?
It is giving out of bound exception : 4
when you are initializing cityList i.e. cityList = arr.toArray(); your array cityList[] = {1,2,3,4} , i.e of size 4 from 0 to 3.
And you are running a for loop i.e
for (int a = 0;a < CITIES;a++)
from a=0 to CITIES , so as the moment arrive when a=4, it gives out of bound error.
I am to find the last ten digits of 1^1 + 2^2 + 3^3.. + 1000^1000.
Is there any way to find this out with pure logic? I think you can't store a number that big.
This question is from a math competition, but I thought of trying to do this in Java.
You don't need to store number that big, you just need the last ten digits. You can store this in a long.
An efficient way to calculate large powers is to multiply and the squares e.g. 19^19 = 19 * 19^2 * 19 ^ 16 = 19 * 19 ^ 2 * 19^2^2^2^2. When you have value which is greater than 10^10 you can truncate the last 10 digits.
BTW the last ten digits of 1000^1000 is 0000000000 and when your add this to your sum, it's the same as adding zero ;)
Edit: While you don't have to use BigInteger, it is simpler to write.
BigInteger tenDigits = BigInteger.valueOf(10).pow(10);
BigInteger sum = BigInteger.ZERO;
for (int i= 1; i <= 1000; i++) {
BigInteger bi = BigInteger.valueOf(i);
sum = sum.add(bi.modPow(bi, tenDigits));
}
sum = sum.mod(tenDigits);
modPow is more efficient than pow with mod seperately as it doesn't have to calculate very large numbers, only the result of the mod.
You could use BigIntegers...
public static void main(String[] args) {
BigInteger acc = BigInteger.ZERO;
for (int k = 1; k <= 1000; k++) {
BigInteger pow = BigInteger.valueOf(k).pow(k);
acc = acc.add(pow);
}
System.out.println(acc);
}
I believe the problem comes from Project Euler, so it's not just a math problem; it should require some computation as well. I don't know how it could be solved with pencil and paper other than by duplicating the calculations a computer might make. I can't see much in the way of a purely mathematical solution. Mathematics can help us optimize the code, however.
To raise a^n, find the binary expansion of n:
n = n_k x 2^k + n_(k-1) x 2^(k-1) + ... + n_0 x 2^0
where n_i = 0 or 1 are the binary digits of n with the zeroth digit on the right. Then
a^n = a^(n_k x 2^k) x a^(n_(k-1) x 2^(k-1)) x ... x a^(n_0 x 2^0).
We can ignore any factors where n_i = 0, since the factor is then a^0 = 1. The process can be written as an algorithm which is O(log n) time and O(1) space (see below).
Next, as a challenge, in order to avoid the use of BigInteger, we can break the calculation into two parts: finding the answer mod 2^10 and finding the answer mod 5^10. In both cases the numbers in the relevant ranges and products of numbers in the relevant ranges fit into longs. The downside is that we have to use the Chinese Remainder Theorem to recombine the results, but it's not that hard, and it's instructive. The hardest part of using the Chinese Remainder Theorem is finding inverses mod m, but that can be accomplished in a straightforward manner using a modification of the Euclidean algorithm.
Asymptotic running time is O(n log n), space is O(1), and everything fits into a few long variables, no BigInteger or other sophisticated library required.
public class SeriesMod1010 {
public static long pow(long a,long n,long m) { // a^n mod m
long result = 1;
long a2i = a%m; // a^2^i for i = 0, ...
while (n>0) {
if (n%2 == 1) {
result *= a2i;
result %= m;
}
a2i *= a2i;
a2i %= m;
n /= 2;
}
return result;
}
public static long inverse(long a, long m) { // mult. inverse of a mod m
long r = m;
long nr = a;
long t = 0;
long nt = 1;
long tmp;
while (nr != 0) {
long q = r/nr;
tmp = nt; nt = t - q*nt; t = tmp;
tmp = nr; nr = r - q*nr; r = tmp;
}
if (r > 1) return -1; // no inverse
if (t < 0) t += m;
return t;
}
public static void main(String[] args) {
long twoTo10 = 1024;
long sum210 = 0;
for (long i=1; i<=1000; i++) {
sum210 += pow(i,i,twoTo10);
sum210 %= twoTo10;
}
long fiveTo10 = 9_765_625;
long sum510 = 0;
for (long i=1; i<=1000; i++) {
sum510 += pow(i,i,fiveTo10);
sum510 %= fiveTo10;
}
// recombine the numbers with the Chinese remainder theorem
long tenTo10 = 10_000_000_000L;
long answer = sum210 * inverse(fiveTo10,twoTo10) * fiveTo10
+ sum510 * inverse(twoTo10,fiveTo10) * twoTo10;
answer %= tenTo10;
System.out.println(answer);
}
}
use BigIntegers :
import java.math.BigInteger;
public class Program {
public static void main(String[] args) {
BigInteger result = new BigInteger("1");
BigInteger temp = new BigInteger("1");
BigInteger I;
for(int i = 1 ; i < 1001 ; i++){
I = new BigInteger(""+i);
for(int j = 1 ; j < i ; j++){
temp = temp.multiply(I);
}
result = result.multiply(temp);
temp = new BigInteger("1");
}
System.out.println(result);
}
}
It can be solved without BigInteger, because you need to store only 10 last digits on every addition or multiplication operation, using % to avoid overflow:
int n = 1000;
long result = 0;
long tenDigits = 10_000_000_000L;
for (int i = 1; i <= n; i++) {
long r = i;
for (int j = 2; j <= i; j++) {
r = (r * i) % tenDigits;
}
result += r;
}
return result % tenDigits;
Complexity is O(N^2), supposed that multiplication runs in constant time.
Answer: 9110846700.
The decimal base uses 0...9 (10 digits) to represent digits, a number that is in the second position right to left represents Digits * base.length^l2rPosition. Using this logics you can create a class that "pretty much does what your primary school teacher told you to, back when we used paper to calculate stuff, but with a baseN number and base-to-base conversions" I have done this class fully functional in C#, but I don't have time to translate it completely to java, this is about the same logics behind java.math.BigInteger. (with less performance I bet for I used a lot of lists >_>" No time to optimize it now
class IntEx {
ArrayList<Integer> digits = new ArrayList<>();
long baseSize = Integer.MAX_VALUE+1;
boolean negative = false;
public IntEx(int init)
{
set(init);
}
public void set(int number)
{
digits = new ArrayList<>();
int backup = number;
do
{
int index = (int)(backup % baseSize);
digits.add(index);
backup = (int) (backup / baseSize);
} while ((backup) > 0);
}
// ... other operations
private void add(IntEx number)
{
IntEx greater = number.digits.size() > digits.size() ? number : this;
IntEx lesser = number.digits.size() < digits.size() ? number : this;
int leftOvers = 0;
ArrayList<Integer> result = new ArrayList<>();
for (int i = 0; i < greater.digits.size() || leftOvers > 0; i++)
{
int sum;
if (i >= greater.digits.size())
sum = leftOvers;
else if(i >= lesser.digits.size())
sum = leftOvers + greater.digits.get(i);
else
sum = digits.get(i) + number.digits.get(i) + leftOvers;
leftOvers = 0;
if (sum > baseSize-1)
{
while (sum > baseSize-1)
{
sum -= baseSize;
leftOvers += 1;
}
result.add(sum);
}
else
{
result.add(sum);
leftOvers = 0;
}
}
digits = result;
}
private void multiply(IntEx target)
{
ArrayList<IntEx> MultiParts = new ArrayList<>();
for (int i = 0; i < digits.size(); i++)
{
IntEx thisPart = new IntEx(0);
thisPart.digits = new ArrayList<>();
for (int k = 0; k < i; k++)
thisPart.digits.add(0);
int Leftovers = 0;
for (int j = 0; j < target.digits.size(); j++)
{
int multiFragment = digits.get(i) * (int) target.digits.get(j) + Leftovers;
Leftovers = (int) (multiFragment / baseSize);
thisPart.digits.add((int)(multiFragment % baseSize));
}
while (Leftovers > 0)
{
thisPart.digits.add((int)(Leftovers % baseSize));
Leftovers = (int) (Leftovers / baseSize);
}
MultiParts.add(thisPart);
}
IntEx newNumber = new IntEx(0);
for (int i = 0; i < MultiParts.size(); i++)
{
newNumber.add(MultiParts.get(i));
}
digits = newNumber.digits;
}
public long longValue() throws Exception
{
int position = 0;
long multi = 1;
long retValue = 0;
if (digits.isEmpty()) return 0;
if (digits.size() > 16) throw new Exception("The number within IntEx class is too big to fit into a long");
do
{
retValue += digits.get(position) * multi;
multi *= baseSize;
position++;
} while (position < digits.size());
return retValue;
}
public static long BaseConvert(String number, String base)
{
boolean negative = number.startsWith("-");
number = number.replace("-", "");
ArrayList<Character> localDigits = new ArrayList<>();
for(int i = number.toCharArray().length - 1; i >=0; i--) {
localDigits.add(number.charAt(i));
}
// List<>().reverse is missing in this damn java. -_-
long retValue = 0;
long Multi = 1;
char[] CharsBase = base.toCharArray();
for (int i = 0; i < number.length(); i++)
{
int t = base.indexOf(localDigits.get(i));
retValue += base.indexOf(localDigits.get(i)) * Multi;
Multi *= base.length();
}
if (negative)
retValue = -retValue;
return retValue;
}
public static String BaseMult(String a, String b, String Base)
{
ArrayList<String> MultiParts = new ArrayList<>();
// this huge block is a tribute to java not having "Reverse()" method.
char[] x = new char[a.length()];
char[] y = new char[b.length()];
for(int i = 0; i < a.length(); i++) {
x[i] = a.charAt(a.length()-i);
}
for(int i = 0; i < b.length(); i++) {
y[i] = a.charAt(a.length()-i);
}
a = new String(x);
b = new String(y);
// ---------------------------------------------------------------------
for (int i = 0; i < a.length(); i++)
{
ArrayList<Character> thisPart = new ArrayList<>();
for (int k = 0; k < i; k++)
thisPart.add(Base.charAt(0));
int leftOvers = 0;
for (int j = 0; j < b.length(); j++)
{
// Need I say repeated characters in base may cause mayhem?
int MultiFragment = Base.indexOf(a.charAt(i)) * Base.indexOf(b.charAt(j)) + leftOvers;
leftOvers = MultiFragment / Base.length();
thisPart.add(Base.charAt(MultiFragment % Base.length()));
}
while (leftOvers > 0)
{
thisPart.add(Base.charAt(leftOvers % Base.length()));
leftOvers = leftOvers / Base.length();
}
char[] thisPartReverse = new char[thisPart.size()];
for(int z = 0; z < thisPart.size();z++)
thisPartReverse[z] = thisPart.get(thisPart.size()-z);
MultiParts.add(new String(thisPartReverse));
}
String retValue = ""+Base.charAt(0);
for (int i = 0; i < MultiParts.size(); i++)
{
retValue = BaseSum(retValue, MultiParts.get(i), Base);
}
return retValue;
}
public static String BaseSum(String a, String b, String Base)
{
// this huge block is a tribute to java not having "Reverse()" method.
char[] x = new char[a.length()];
char[] y = new char[b.length()];
for(int i = 0; i < a.length(); i++) {
x[i] = a.charAt(a.length()-i);
}
for(int i = 0; i < b.length(); i++) {
y[i] = a.charAt(a.length()-i);
}
a = new String(x);
b = new String(y);
// ---------------------------------------------------------------------
String greater = a.length() > b.length() ? a : b;
String lesser = a.length() < b.length() ? a : b;
int leftOvers = 0;
ArrayList<Character> result = new ArrayList();
for (int i = 0; i < greater.length() || leftOvers > 0; i++)
{
int sum;
if (i >= greater.length())
sum = leftOvers;
else if (i >= lesser.length())
sum = leftOvers + Base.indexOf(greater.charAt(i));
else
sum = Base.indexOf(a.charAt(i)) + Base.indexOf(b.charAt(i)) + leftOvers;
leftOvers = 0;
if (sum > Base.length()-1)
{
while (sum > Base.length()-1)
{
sum -= Base.length();
leftOvers += 1;
}
result.add(Base.charAt(sum));
}
else
{
result.add(Base.charAt(sum));
leftOvers = 0;
}
}
char[] reverseResult = new char[result.size()];
for(int i = 0; i < result.size(); i++)
reverseResult[i] = result.get(result.size() -i);
return new String(reverseResult);
}
public static String BaseConvertItoA(long number, String base)
{
ArrayList<Character> retValue = new ArrayList<>();
boolean negative = false;
long backup = number;
if (negative = (backup < 0))
backup = -backup;
do
{
int index = (int)(backup % base.length());
retValue.add(base.charAt(index));
backup = backup / base.length();
} while ((backup) > 0);
if (negative)
retValue.add('-');
char[] reverseRetVal = new char[retValue.size()];
for(int i = 0; i < retValue.size(); i++)
reverseRetVal[i] = retValue.get(retValue.size()-i);
return new String(reverseRetVal);
}
public String ToString(String base)
{
if(base == null || base.length() < 2)
base = "0123456789";
ArrayList<Character> retVal = new ArrayList<>();
char[] CharsBase = base.toCharArray();
int TamanhoBase = base.length();
String result = ""+base.charAt(0);
String multi = ""+base.charAt(1);
String lbase = IntEx.BaseConvertItoA(baseSize, base);
for (int i = 0; i < digits.size(); i++)
{
String ThisByte = IntEx.BaseConvertItoA(digits.get(i), base);
String Next = IntEx.BaseMult(ThisByte, multi, base);
result = IntEx.BaseSum(result, Next, base);
multi = IntEx.BaseMult(multi, lbase, base);
}
return result;
}
public static void main(String... args) {
int ref = 0;
IntEx result = new IntEx(0);
while(++ref <= 1000)
{
IntEx mul = new IntEx(1000);
for (int i = 0; i < 1000; ++i) {
mul.multiply(new IntEx(i));
}
result.add(mul);
}
System.out.println(result.toString());
}
}
Disclaimer: This is a rough translation/localization from a C# study, there are lots of code omitted. This is "almost" the same logics behind java.math.BigInteger (you can open BigInteger code on your favorite designer and check for yourself. If may I be forgetting a overloaded operator behind not translated to java, have a bit of patience and forgiveness, this example is just for a "maybe" clarification of the theory.
Also, just a sidenote, I know it is "Trying to reinvent the wheel", but considering this question has academic purpose I think its fairly rasonable to share.
One can see the result of this study on gitHub (not localized though), I'm not expanding that C# code here for its very extensive and not the language of this question.
This gives the correct answer without excess calculations. A Long is sufficient.
public String lastTen() {
long answer = 0;
String txtAnswer = "";
int length = 0;
int i = 1;
for(i = 1; i <= 1000; i++) {
answer += Math.pow(i, i);
txtAnswer = Long.toString(answer);
length = txtAnswer.length();
if(length > 9) break;
}
return txtAnswer.substring(length-10);
}