How to print all possible sequences of a number n - java

I am trying to print all possible sequences of n and I don't know where I went wrong.
Example: If I let n = 3, then I have to get 33 possible combinations.
import java.util.Scanner;
public class MyPermutations {
public static void show(int[] a) {
for (int i = 0; i < a.length; i++)
System.out.printf("%d", a[i]);
System.out.printf("\n");
}
public static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static boolean hasNext(int[] a) {
int N = a.length;
// find rightmost element a[k] that is smaller than element to its right
int k;
for (k = N-2; k >= 0; k--)
if (a[k] < a[k+1]) break;
if (k == -1) return false;
// find rightmost element a[j] that is larger than a[k]
int j = N-1;
while (a[k] > a[j])
j--;
swap(a, j, k);
for (int r = N-1, s = k+1; r > s; r--, s++)
swap(a, r, s);
return true;
}
public static void perm(int N) {
// initialize permutation
int[] a = new int[N];
for (int i = 1; i < N; i++) {
a[0]=1;
a[i] = i+1;
}
// print permutations
show(a);
while (hasNext(a))
show(a);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = Integer.parseInt(sc.next());
perm(N);
}
}
Input:
3
My Output:
123 132 213 231 312 321
Expected Output:
111 112 113 121 122 123 131 132 133
211 212 213 221 222 223 231 232 233
311 312 313 321 322 323 331 332 333

Forget about swap, and start over.
Think of it like incrementing a number, except you can only use digits 1-N.
E.g. for N=4, start with 1111. Print it.
Increment to 1112, then 1113, then 1114.
Next increment carries over, so 1121, 1122, ..., 1144.
Handle multiple carry overs, 1211.
And so on until you reach 4444, and you're done.
Of course, you could just loop through the N^N combinations, and use division and remainder to build to "digits" for each combination:
private static void perm(int n) {
char[] digits = new char[n];
final int combinations = (int)Math.pow(n, n);
for (int i = 0; i < combinations; i++) {
for (int num = i, j = n - 1; j >= 0; num /= n, j--)
digits[j] = (char)('1' + num % n);
System.out.print(digits);
System.out.print((i + 1) % (n * n) == 0 ? System.lineSeparator() : " ");
}
}
Output
// perm(1)
1
// perm(2)
11 12 21 22
// perm(3)
111 112 113 121 122 123 131 132 133
211 212 213 221 222 223 231 232 233
311 312 313 321 322 323 331 332 333
// perm(4)
1111 1112 1113 1114 1121 1122 1123 1124 1131 1132 1133 1134 1141 1142 1143 1144
1211 1212 1213 1214 1221 1222 1223 1224 1231 1232 1233 1234 1241 1242 1243 1244
1311 1312 1313 1314 1321 1322 1323 1324 1331 1332 1333 1334 1341 1342 1343 1344
1411 1412 1413 1414 1421 1422 1423 1424 1431 1432 1433 1434 1441 1442 1443 1444
2111 2112 2113 2114 2121 2122 2123 2124 2131 2132 2133 2134 2141 2142 2143 2144
2211 2212 2213 2214 2221 2222 2223 2224 2231 2232 2233 2234 2241 2242 2243 2244
2311 2312 2313 2314 2321 2322 2323 2324 2331 2332 2333 2334 2341 2342 2343 2344
2411 2412 2413 2414 2421 2422 2423 2424 2431 2432 2433 2434 2441 2442 2443 2444
3111 3112 3113 3114 3121 3122 3123 3124 3131 3132 3133 3134 3141 3142 3143 3144
3211 3212 3213 3214 3221 3222 3223 3224 3231 3232 3233 3234 3241 3242 3243 3244
3311 3312 3313 3314 3321 3322 3323 3324 3331 3332 3333 3334 3341 3342 3343 3344
3411 3412 3413 3414 3421 3422 3423 3424 3431 3432 3433 3434 3441 3442 3443 3444
4111 4112 4113 4114 4121 4122 4123 4124 4131 4132 4133 4134 4141 4142 4143 4144
4211 4212 4213 4214 4221 4222 4223 4224 4231 4232 4233 4234 4241 4242 4243 4244
4311 4312 4313 4314 4321 4322 4323 4324 4331 4332 4333 4334 4341 4342 4343 4344
4411 4412 4413 4414 4421 4422 4423 4424 4431 4432 4433 4434 4441 4442 4443 4444

If you look at your output, the problem is obvious. You are not accounting for multiple instances of the same number (i.e. 2 2's or 3 3's).

If you want all possible permutations your code is just fine, as permutations are made from swapping elements only and not reusing them.
If you want to build all possible combinations (including aaa, aab, etc.) instead it won't be enough to just swap the elements.
public List<String> combinations(List<Character> elements) {
List<String> combinations = new ArrayList<>();
if (elements.isEmpty()) {
return combinations;
}
if (elements.size() == 1) {
combinations.add(String.valueOf(elements.get(0)));
return combinations;
}
for (int i = 0; i < elements.size(); i++) {
int current = elements.get(i);
List<String> subCombinations = combinations(elements);
StringBuilder builder;
for (String s : subCombinations) {
builder = new StringBuilder();
builder.append(current).append(s);
combinations.add(builder.toString());
}
}
return combinations;
}

Related

How to create a matrix using predetermined row, column, and value numbers in a string Java

I am stuck and need helpful input with my beginner code. I have a text file that contains:
{001 012 023 034 045 056 067 078 089 102 113 124 135 146 157 168 179 181 203 214 225 236 247 258 269 271 282 304 315 326 337 348 359 361 372 383 405 416 427 438 449 451 462 473 484 506 517 528 539 541 552 563 574 585 607 618 629 631 642 653 664 675 686 708 719 721 732 743 754 765 776 787 809 811 822 833 844 855 866 877 888}
Each triplet corresponds to the X and Y axis for the first two numbers and the value to put in this index is the third one.
Step 1) I buffered in the text and removed spaces to isolate each value(X,Y,Z) in its own string to ease use further out.
Step 2) I convert a specific character in each string to INT giving me 3 values I can then insert manually in my 9X9 matrix.
Step 3) For now I can manually select the index and populate one value in the matrix(in this example, in the code I selected index 8), I need to do this for all values in a loop but can't seem to figure out how to go forward with this.
Code:
import java.io.*;
public class readBuffer {
static void theBuffer() throws IOException {
File file = new File("D://Documents/-/DOCS/School/Prog/game1.txt");
String xString = ""; //three strings used for the coordinates
String yString = "";
String zString = "";
int[][] tab = new int[9][9]; //9X9 matrix created
try (
//read file
FileReader aFile = new FileReader(file);
//
BufferedReader theBuffer = new BufferedReader(aFile);
) {
//Conversion to a String of characters
String string = theBuffer.readLine();
//removes spaces in the string
string = string.replaceAll("\\s", "");
//Loop that generates the X,Y,Z coord and value strings
//Row X (1st value in the triplet)
for (int i = 0, n = string.length(); i < n; i++) {
if ((i + 2) % 3 == 2)
xString += (string.charAt(i));
}
//Column Y (2nd value in the triplet)
for (int i = 0, n = string.length(); i < n; i++) {
if ((i + 1) % 3 == 2)
yString += (string.charAt(i));
}
//Value Z (3rd value in the triplet)
for (int i = 0, n = string.length(); i < n; i++) {
if (i % 3 == 2)
zString += (string.charAt(i));
}
//Visualization for testing
System.out.println("Row #:" + xString);
System.out.println("Col #:" + yString);
System.out.println("Num #:" + zString);
int x = Character.getNumericValue(xString.charAt(8)); //Convert specific char to an INT
int y = Character.getNumericValue(yString.charAt(8)); //Convert specific char to an INT
int z = Character.getNumericValue(zString.charAt(8)); //Convert specific char to an INT
//Visualization for testing
System.out.println("");
System.out.println("//Converted INT numbers//");
System.out.println("Row #:" + x);
System.out.println("Col #:" + y);
System.out.println("Num #:" + z);
//Loop that generates then 9X9 matrix
tab[x][y] = z;
System.out.println("");
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++)
System.out.print(tab[i][j] + " ");
System.out.println();
}
} catch (IOException e) {
System.out.println(e);
}
}
public static void main(String[] args) throws IOException {
theBuffer();
}
}
Image of console Result
Need to fill this out and that is where I need advice.
Seems like you should just iterate the "triplets" and extract the 3 digits.
static int[][] parseMatrix(String values) {
int[][] matrix = new int[9][9];
for (String triplet : values.split(" ")) {
int row = Character.digit(triplet.charAt(0), 10);
int col = Character.digit(triplet.charAt(1), 10);
int val = Character.digit(triplet.charAt(2), 10);
matrix[row][col] = val;
}
return matrix;
}
Test
int[][] matrix = parseMatrix("001 012 023 034 045 056 067 078 089" +
" 102 113 124 135 146 157 168 179 181" +
" 203 214 225 236 247 258 269 271 282" +
" 304 315 326 337 348 359 361 372 383" +
" 405 416 427 438 449 451 462 473 484" +
" 506 517 528 539 541 552 563 574 585" +
" 607 618 629 631 642 653 664 675 686" +
" 708 719 721 732 743 754 765 776 787" +
" 809 811 822 833 844 855 866 877 888");
for (int[] row : matrix) {
for (int value : row)
System.out.print(value + " ");
System.out.println();
}
Output
1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9 1
3 4 5 6 7 8 9 1 2
4 5 6 7 8 9 1 2 3
5 6 7 8 9 1 2 3 4
6 7 8 9 1 2 3 4 5
7 8 9 1 2 3 4 5 6
8 9 1 2 3 4 5 6 7
9 1 2 3 4 5 6 7 8

Rearrange Array Alternately

Given a sorted array of positive integers. Your task is to rearrange the array elements alternatively i.e first element should be max value, second should be min value, third should be second max, fourth should be second min and so on.
class RearrangeAlternate{
public void swapMax(int arr[], int i, int n){
int x = arr[i];
int j;
for(j = n-1; j>i; j--){
if(arr[j] > x){
break;
}
}
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public void swapMin(int arr[], int i, int n){
int x = arr[i];
int j;
int res = n-1;
for(j = n-1; j>i; j--){
if(arr[j] < x){
if(arr[j] < arr[res]){
res = j;
}
}
}
int temp = arr[i];
arr[i] = arr[res];
arr[res] = temp;
}
public void rearrange(int arr[], int n){
for(int i = 0; i<n; i++){
if(i%2 == 0){
swapMax(arr, i, n);
}
else swapMin(arr, i, n);
}
}
}
Please help me find the error
It is showing wrong output for somecases.
eg.
82
12 23 28 43 44 59 60 68 70 85 88 92 124 125 136 168 171 173 179 199 212 230 277 282 306 314 316 325 328 336 337 363 365 368 369 371 374 387 394 414 422 427 430 435 457 493 506 527 531 538 541 546 568 583 650 691 730 737 751 764 778 783 785 789 794 803 809 815 847 858 863 874 887 896 916 920 926 927 930 957 981 997
My codes output: 997 12 981 23 957 28 930 43 927 44 926 59 920 60 916 68 896 70 887 85 874 88 863 92 858 124 847 125 815 136 809 168 803 171 794 173 789 179 785 199 783 212 778 230 764 277 751 282 737 306 730 314 691 316 650 325 568 328 527 336 506 337 430 363 374 369 541 365 583 368 531 371 493 387 538 394 457 414 435 422 546 427
Answer: 997 12 981 23 957 28 930 43 927 44 926 59 920 60 916 68 896 70 887 85 874 88 863 92 858 124 847 125 815 136 809 168 803 171 794 173 789 179 785 199 783 212 778 230 764 277 751 282 737 306 730 314 691 316 650 325 583 328 568 336 546 337 541 363 538 365 531 368 527 369 506 371 493 374 457 387 435 394 430 414 427 422
Since your array is sorted, you can simply do it as follows:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int temp;
for (int i = 0; i < arr.length; i++) {
if (i % 2 == 0) {
// Store the last element to 'temp'
temp = arr[arr.length - 1];
// Shift all elements, starting from index, 'i', to one place right
for (int j = arr.length - 2; j >= i; j--) {
arr[j + 1] = arr[j];
}
// Put the value stored in 'temp' to index, 'i'
arr[i] = temp;
}
}
System.out.println(Arrays.toString(arr));
}
}
Output:
[10, 1, 9, 2, 8, 3, 7, 4, 6, 5]
Since the array is sorted and we need to rearrange alternatively,we can use the technique to store two numbers at a single position in such a manner that we are also able to retrieve back the original element when required.
Let's say we need to store n1 and n2 at same position then we can formulate it like :
====================== n1 = n1 + (n2%z)*z ======================
To extract n1 we can modulo n1 by z and to extract n2 we can divide n1 by z.
For more detailed explanation,you can refer this video : https://youtu.be/KOglcclYgXI
using lambda — doing the rearranging outside the original arr
O(n) time complexity
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
int[] tmp = IntStream.range( 0, (arr.length + 1) / 2 )
.flatMap( n -> IntStream.of( arr[arr.length - n - 1], arr[n] ) ).toArray();
System.arraycopy( tmp, 0, arr, 0, arr.length );
gets for arr: [11, 1, 10, 2, 9, 3, 8, 4, 7, 5, 6]
The solution mentioned below solves the problem in O(N) Time complexity and O(1) Space Complexity WITHOUT using the "storing 2 values at one location concept". Moreover this algorithm can also handle duplicate values & float values given the input list is non-decreasingly sorted and consists of positive real numbers only.
PS: If you wish you can modify my algorithm slightly to make it work for negative values as well.
Please don't get intimidated by looking at the code. Implementation is very simple. Algorithm might be a bit tricky to understand.
def reArrange(arr, print_arr_state=True):
# arr: non-decreasingly sorted list of positive floats/ints
length = len(arr)
for i in range(length):
if arr[i] > 0:
cycler(arr, i, length, print_arr_state)
arr[i] = abs(arr[i]) # This is the tricky part
# printing the array after every iteration
if print_arr_state:
print('after', i, 'th iteration:', arr)
def cycler(arr, start_index, length, print_cycler_array=True):
if print_cycler_array:
print('cycler function:', arr, end=' ---> ')
half_length_index = length // 2
swap_index = start_index
current_value = arr[start_index]
while True:
if swap_index < half_length_index:
swap_index = 2 * swap_index + 1
else:
swap_index = 2 * (length - 1 - swap_index)
# Placing the current value at swap_index and making the making current_value variable refer to the value which was at swap_index
swap_value = arr[swap_index]
arr[swap_index] = -1 * current_value # -1 * ?? This is the tricky part of the algo
current_value = swap_value
# cycler function will not stop until the simple cycle is complete
# simple cycle is complete when swap_index == start_index
if swap_index == start_index:
if print_cycler_array:
print(arr)
return
Giving Input (input_array) and Calling reArrange function:
input_array = [0.1, 2, 3.2, 3.3, 3.3, 4, 5.7, 5.7, 6.8, 7, 8, 9]
reArrange(input_array)
Output:
answer_array = [9, 0.1, 8, 2, 7, 3.2, 6.8, 3.3, 5.7, 3.3, 5.7, 4]
Understanding the algorithm
Tricky part of the algorithm:
Every value belongs to exactly 1 cycle and this cycle is a simple cycle (simple cycle vs complex cycle in graphs). One execution of cycler function corresponds to one cycle which is also a simple cycle.
Whenever I cover a value during a cycle, I multiply it with -1 (to indicate that it is covered) and store it in the input array itself.
During the i-th iteration of the loop of reArrange function, if I find the i-th value to be negative I get an indication that this value is a part of a cycle executed for some j-th iteration (where j < i), thus I don't call the cycler function on this value. But if this value is positive (indicating that none of cycles executed so far has covered this value), it implies that it is not covered yet and hence should be covered in the i-th iteration using the cycler function.
But wait!, if I have multiplied all values with -1 my final answer will be -1 * correct_answer_array. To solve this problem, one solution is to reiterate my answer_array (which was input_array initially and now has transformed to my answer_array) and take the absolute of each value OR I can do the same thing during my first and only iteration (of reArrange function's loop) by taking the absolute of the value before moving to the i+1-th iteration.
Some valid questions
There are few aspects of this algorithm that I haven't covered in this post. Let me leave you with some of these aspects in the form of questions:
Is the while loop of cycler function guaranteed to terminate?
Why should we not cover a value more than once?
How can we handle the negative input values (if any)?
Isn't a single cycle sufficient to cover all the values of the input_array. (Isn't a single call of the cycler function sufficient to cover all the values)?
Hint: eg: 1 2 3 4 5 6 7, this example will lead to 3 cycles. (cycler function will be called thrice)
What happens during a single call of cycler function?
Hint: Every value which is the part of this cycle shifts to the place where it is supposed to be in the correct_answer_array. Once a value is at its correct place, it should not be disturbed again.
Please visit the comments section at the bottom of this page (GeeksforGeeks) to see the dry run of the algorithm. Please make sure you read all of the comments by me because I have created a bit of mess there.
Given a sorted array of positive integers. Your task is to rearrange the array elements alternatively i.e first element should be max value, second should be min value, third should be second max, fourth should be second min and so on.
//c#
using System;
using System.Collections.Generic;
using System.Text;
namespace vijay
{
class oddEven
{
public static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[n];
for(int i=0;i<n;i++)
arr[i]=Convert.ToInt32(Console.ReadLine());
// example input int[] arr = {8,7,6,5,4,3,2,1 };
Array.Sort(arr); //sorting array
Array.Sort(arr);
int f = 1,f1=0;
int[] dummy = new int[n];
int a = arr.Length / 2;
for(int i=0;i<n;i++)
{
if(i<a) //first half add in even position
{
dummy[f]=arr[i];
f += 2;
}
else //second half add in odd positions
{
dummy[f1] = arr[i];
f1 += 2;
}
}
Console.WriteLine("\n\n\n\n"); //print the result
foreach(int q in dummy)
{
Console.WriteLine(q);
}
}
}
}
//python
list=[2,5,8,9,4,6,7,1]
a=sorted(list)
b=reversed(sorted(list))
c=a[0:len(a)//2]
d=a[len(a)//2:][::-1]
for i in range(len(c)):
print(d[i],end=' ')
print(c[i],end=' ')

How can I find the max number in the code?

I want my code to print out 10 numbers per line and count how many numbers there are. I also want to be able to find the max number. I am having trouble figuring out how to find the max. Here is my code.
int valCount = 0;
int numCount =0;
while (startingNum > 1) {
int count = 0;
System.out.print(startingNum + " ");
valCount++;
if(valCount%10 ==0)
System.out.println();
if (startingNum % 2==0) {
startingNum = startingNum/2;
numCount++;
} else {
startingNum = (startingNum*3) +1;
numCount++;
}
}
This is the correct code:
public static void main(String[] args) {
int startingNum = 27;
int counter = 0;
while (startingNum > 1) {
counter++;
System.out.print(startingNum + " ");
if (counter % 10 == 0)
System.out.println();
if (startingNum % 2 == 0) {
startingNum = startingNum / 2;
} else {
startingNum = (startingNum * 3) + 1;
}
}
System.out.println(1);
}
You can use a counter, increment it at each print, when you reach a multiple of 10 print a new line, also to align the different elements, I would suggest to use printf, here I set to %5d because max number has 4 digit, if it goes up to like 6 digit use %7d
int valCount = 0;
while (startingNum > 1) {
System.out.printf("%5d", startingNum);
valCount++;
if(valCount%10 ==0)
System.out.println();
if (startingNum % 2==0) {
startingNum = startingNum/2;
} else {
startingNum = (startingNum*3) +1;
}
}
System.out.printf(" 1");
The Demo code will give you :
27 82 41 124 62 31 94 47 142 71
214 107 322 161 484 242 121 364 182 91
274 137 412 206 103 310 155 466 233 700
350 175 526 263 790 395 1186 593 1780 890
445 1336 668 334 167 502 251 754 377 1132
566 283 850 425 1276 638 319 958 479 1438
719 2158 1079 3238 1619 4858 2429 7288 3644 1822
911 2734 1367 4102 2051 6154 3077 9232 4616 2308
1154 577 1732 866 433 1300 650 325 976 488
244 122 61 184 92 46 23 70 35 106
53 160 80 40 20 10 5 16 8 4
2 1

Program Displays the number of Mersenne wrong

hi guys the problem that im having with this code is that the number of mersenne primes is supposed to be 4 but it outputs 8. i know this because the number of Mersenne primes between 1 and 1000 are 3, 7, 31, and 127 but it also outputs 15, 63, 255, and 511. which i dont know why. is there also a way to output the counts of Primes per 100 numbers? thanks
public static void main(String[] args) {
System.out.println("Prime numbers between 1 and 1000 are\n");
String message = "";
String message2 = "";
// loop numbers from 1 to 1,000, printing only the primes
int counter2 = 0;
int counter = 0;
for( int number s= 2; number <= 1000; number ++){
if(isPrime(number)) {
counter++;
if(counter % 10 == 0) {
System.out.println(number);
}
else
System.out.print(number + " ");
}
}
for(int number2 = 2; number2 <= 1000; number2 ++){
if(isMersenne(number2)){
counter2++;
System.out.print(number2 + "*");
}
}
System.out.print( "\n\n The number of primes between 1 and 1000 are " + counter);
System.out.print( "\n The number of Mersennes is " + counter2);
}
public static boolean isPrime( int number ){
// initialize the boolean variable prime to true
boolean isPrime = true;
for(int divisor = 2; divisor <= number /2; divisor++) {
if(number % divisor == 0) {
isPrime = false;
}
}
return isPrime;
}
public static boolean isMersenne(int number){
// declare and initialize variable powTwo to 2
int powTwo = 2;
boolean mersenne = false;
while(powTwo <= number){
powTwo *= 2;
if(powTwo - number == 1)
// if the prime is one less than a power of 2, return true
mersenne = true;
}
return mersenne;
} // end method isMersenne
}
this is the output of my program
Prime numbers between 1 and 1000 are
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463
467 479 487 491 499 503 509 521 523 541
547 557 563 569 571 577 587 593 599 601
607 613 617 619 631 641 643 647 653 659
661 673 677 683 691 701 709 719 727 733
739 743 751 757 761 769 773 787 797 809
811 821 823 827 829 839 853 857 859 863
877 881 883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997 3*7*15*31*63*127*255*511*
The number of primes between 1 and 1000 are 168
The number of Mersennes is 8
Your problem is that isMersenne is just checking whether the number is one less than a power of two. It's not also checking that it's a prime.
You need to change your isMersenne method so that it calls isPrime after checking whether the number is one less than a power of two. If isPrime returns false, then isMersenne should also return false.

Java: What is the best way to add odd numbers in order to get 1 4 9 16 as output

I know how to display the odd numbers, but can't figure out how to display the sum of odd numbers in order to get 1 4 9 16 25 36 49 64 81 100 output
the idea is to use
1=1
1+3=4
4+5=9
and so on
The idea is to avoid multiplication. (I know it would be the easiest solution.)
What I have so far is:
public static void main(String[] args) {
for(int i=1; i <= 100; i++){
if( i % 2 != 0){
System.out.print(i + " ");
}
}
}
You have the loop. All you are missing is the addition :
int num = 0;
for(int i=1; i <= 100; i++){
if( i % 2 != 0) {
num = num + i;
System.out.print(num + " ");
}
}
If the intention is to avoid multiplication, then replacing that with division (or rather remainder) seems meaningless.
What you want is to use the += operator:
int num = 0;
for (int i = 1; i <= 100; i += 2) {
num += i;
System.out.print(num + " ");
}
Output
1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 784 841 900 961 1024 1089 1156 1225 1296 1369 1444 1521 1600 1681 1764 1849 1936 2025 2116 2209 2304 2401 2500
Note: This is just an optimized version of the answer by Eran.
As they are squares: The difference between two squares is always its base two times minus 1:
int num = 0;
for(int i=1; i <= 100; i++){
num += i+i-1;
System.out.print(i + " ");
}

Categories