Convert algorithm to a formula

Click For Summary
SUMMARY

The discussion focuses on converting a specific algorithm written in C-like pseudocode into a mathematical formula. The algorithm counts occurrences based on the condition involving the floor function and integer comparisons. Key simplifications include replacing the nested loop with a direct count using the expression c+=floor(x/i)-i+1 and eliminating the floor function by reformulating the condition to if(i^2 <= x). The final simplified function retains the core logic while improving efficiency.

PREREQUISITES
  • Understanding of algorithm complexity and optimization techniques
  • Familiarity with integer arithmetic and floor functions
  • Proficiency in programming concepts, particularly loops and conditional statements
  • Basic knowledge of mathematical notation and inequalities
NEXT STEPS
  • Research mathematical summation techniques for discrete functions
  • Explore the implications of integer inequalities in algorithm design
  • Learn about optimization strategies for nested loops in algorithms
  • Investigate the use of floor functions in mathematical proofs and algorithms
USEFUL FOR

Mathematicians, computer scientists, and software developers interested in algorithm optimization and mathematical modeling of code.

mryoussef2012
Messages
6
Reaction score
0
Hi
Please can someone help me convert this algorithm to a mathematical formula ?

function fun(int x)
{
int c = 0 ;
for(int i=2;i<floor(x/2);i++)
{
if(floor(x/i) > i-1)
for(int j=0;j<floor(x/i)-i+1;j++)
c++;
}

return c;
}

thanks
 
Physics news on Phys.org
Code:
for(int j=0;j<floor(x/i)-i+1;j++)
  c++;

This just counts how many times j<floor(x/i)-i+1.
In other words, you can replace it with
c+=floor(x/i)-i+1;

Next:
if(floor(x/i) > i-1)
As the left side cannot increase (with increasing i) and the right side always increases, this is true up to some specific i. Both sides are integers, so the statement is equivalent to
if(floor(x/i) >= i)
Written in that way, it is possible to drop floor() completely (check this!) as i is an integer:
if(x/i >= i)
which is just
if(i^2 <= x)

Simplified code:
Code:
function fun(int x)
{
  int c = 0 ;
  for(int i=2;i<floor(x/2);i++)
  {
    if(i^2 <= x)
      c+=floor(x/i)-i+1;
  }
  return c;
}

Now you have two upper limits for i, so it is reasonable to split that in two cases. Can you find them? The border is a specific integer.
It could be tricky (or even impossible) to find an explicit way to sum those floor(x/i), but it is certainly possible to write it as a sum in a formula.
 
Thanks mfb , that was great
 

Similar threads

Replies
2
Views
6K
Replies
2
Views
2K
Replies
12
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 17 ·
Replies
17
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
1
Views
2K
  • · Replies 18 ·
Replies
18
Views
3K
Replies
1
Views
2K
  • · Replies 13 ·
Replies
13
Views
2K