Click here to Skip to main content
15,890,670 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Java
<pre>static void fun(int x) {
int a, b, c, d;
d = 1;
for (a = 1; a <= x; a++) {
b = a;
c = 1;
while (b > 0) {
c &= b % 2;
b /= 2;
}
d += c;
}
 System.out.println(d);
}


What I have tried:

I have tried to change the while loop into if loop and then after the loop assigns the new values to the variables, I have tried to use continue; but results has been completely different. I have also attempted to get rid of the for loop and increment the a value without a loop but result has been different also.
Posted
Updated 13-Apr-19 12:52pm

Java
static void very_fun(int x)
{
  int b = 1, c = 1;
  for (int a = 1; a <= x; a += b)
  {
    ++c;
    b *= 2;
  }
  System.out.println(c);
}
 
Share this answer
 
What you need is a recursive function.

java recursive functions at DuckDuckGo[^]
 
Share this answer
 
Quote:
I have tried to use continue; but results has been completely different.

Trying random changes in code is a bad idea.

Learn to indent properly your code, it show its structure and it helps reading and understanding. It also helps spotting structures mistakes.
C++
static void fun(int x) {
	int a, b, c, d;
	d = 1;
	for (a = 1; a <= x; a++) {
		b = a;
		c = 1;
		while (b > 0) {
			c &= b % 2;
			b /= 2;
		}
		d += c;
	}
	System.out.println(d);
}

Indentation style - Wikipedia[^]

Professional programmer's editors have this feature and others ones such as parenthesis matching and syntax highlighting.
Notepad++ Home[^]
ultraedit[^]
Quote:
How can I write the same function by using exactly one loop

On first reading, it looks like the 2 loops are needed, so if you have to keep it in 1 function, you need to fully understand what is doing this code.

This
C++
c &= b % 2;
b /= 2;

tells that the code is messing with the binary form of b

first thing to do is run the function with x=1, 2, 3, 4 ... 16
note matching results and binary of x
x binary result
  1    1
  2   10
  3   11
...

then you have to find the reason why result change, this understanding may lead to simplify and a loop removal.
Otherwise, CPallini's solution is just magic and you will learn nothing.
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900