Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For Loops Code Optimization

I had a challenge to print out multiples of 7 (non-negative) to the 50th multiple in the simplest way humanly possible using for loops.

I came up with this (Ignoring the data types)

for(int i = 0; i <= 350; i += 7)
         {System.out.println(i);}

The other guy came up with this

for(int i=0;i <=50; i++)
{
System.out.println(7*i);
}

However, I feel the two code snippets could be further optimized. If it actually can please tell. And what are the advantages/disadvantages of one over the other?

like image 382
Mob Avatar asked Mar 12 '26 11:03

Mob


2 Answers

If you really want to optimize it, do this:

System.out.print("0\n7\n14\n21\n28\n35\n42\n49\n56\n63\n70\n77\n84\n91\n98\n105\n112\n119\n126\n133\n140\n147\n154\n161\n168\n175\n182\n189\n196\n203\n210\n217\n224\n231\n238\n245\n252\n259\n266\n273\n280\n287\n294\n301\n308\n315\n322\n329\n336\n343\n350");

and it's O(1) :)

like image 93
Eng.Fouad Avatar answered Mar 14 '26 03:03

Eng.Fouad


The first one technically performs less operations (no multiplication).

The second one is slightly more readable (50 multiples of 7 vs. multiples of 7 up to 350).

Probably can't be optimized any further.

Unless you're willing to optimize away multiple println calls by doing:

StringBuilder s = new StringBuilder();

for(int i = 0; i <= 350; i += 7) s.append(i).append(", ");

System.out.println(s.toString());

(IIRC printlns are relatively expensive.)

This is getting to the point where you gain a tiny bit of optimization at the expense of simplicity.

like image 37
trutheality Avatar answered Mar 14 '26 03:03

trutheality