What is a way to simulate division using only multiplication and whole numbers?

The issue at hand:

The stack-building API that I'm currently using in rapidweaver has limitations when it comes to division or floats, making it challenging to perform certain mathematical operations.

Insights into the API's rules:

This particular API is incorporated within html, css, and javascript files, which are compiled into actual html, css, and javascript during the project file generation process.

  1. Every mathematical operation within this API is enclosed in:

    %( math )%

  2. For example, to calculate (1 + 3) * 6, the format would be:

    %( %( 1 + 3 )% * 6 )%

    Attempting to use %( 1 + 3 * 6 )% would lead to an error, as only one operation is allowed within each %()%.

  3. Additionally, it's possible to use variables that represent user input

    %id=variableName%

  4. Therefore, if the goal is to double the user input, the code would look like:

    %( %id=variableName% * 2 )%

The objective at hand:

%( %id=CB_seconds% / 2 )% OR %( %id=CB_seconds% * 0.5 )%

Unfortunately, the API restricts the use of the above expressions for reasons unknown...

The desired outcome is to take the user-defined input %id=CB_seconds%, and divide it by half. The user will input a value between 0 and 10,000 as an integer. Both the original value and the halved value need to be displayed separately. One workaround could involve asking the user to enter a value between 0 and 5,000 and then multiplying it by two. However, this solution is not ideal as it increases complexity for the user who is setting the animation length.

The Query:

Is there a method to obtain half of a number using only integers and multiplication/addition/subtraction, without prior knowledge of the number?


For more information on the Stacks API documentation, visit -

Answer №1

It is impossible to create a function using only addition and multiplication.

This is a mathematical concept:

If you were to try to create a function using only addition and multiplication, it would eventually lead to a polynomial function such as:

a/b=f(a,b)

When you analyze this function as n grows to infinity

You will find that f(n,n)=n/n=1

However, polynomials always approach +infinity, -infinity, or 0, making it impossible for such a function to exist.

Answer №2

Just like multiplication can be thought of as a series of additions, division can be seen as a series of subtractions. In order to achieve this, you must have the ability to loop and compare values. For dividing a by b, assuming both are integers and a is greater than b, the pseudocode would look something like this:

division = 1
c = a - b
while (c > b)
  c = c - b
  division = division + 1
end while

After running this code, you will have a / b = division and the remainder as c.

Let's take an example with a = 10 and b = 3:

division = 1
c = 10 - 3 = 7

c (= 7) > 3 --> Continue
  c = 7 - 3 = 4
  division = 2

c (= 4) > 3 --> Continue
  c = 4 - 3 = 1
  division = 3

c (= 1) < 3 --> Stop

After running this, you will find that division = 3 and c = 1, which means 10 / 3 = 3 (+ 1).

It seems the Stacks API allows for comparison. If it also supports looping, then you can use the aforementioned method.

In conclusion, it's quite silly that a division operation is not readily available.

Answer №3

Admittedly, this may not be the most efficient coding technique, but one approach could be to iterate through each number from 1 to 5000, doubling it, and then checking to see if it matches the original input number (also checking for the number + 1 to account for rounded fractions). With only 5000 operations needed, the impact on performance should be minimal.

Answer №4

Fresh response

Given the absence of loops, a binary search must be implemented. The approach involves:

CB_copy = CB_seconds;
CB_half = 0;
for ( exp = 13 ; exp > 0 ; exp- - ) {
    if ( CB_copy > 1 << exp ) {
        CB_half += 1 << (exp-1);
        CB_copy -= 1 << exp;
    }
}

However, lacking conditionals compels a revision using available comparisons:

CB_copy = CB_seconds;
CB_half = 0;
for ( exp = 13 ; exp > 0 ; exp- - ) {
    CB_half += ( 1 << (exp-1) ) * ( CB_copy > 1 << exp );
    CB_copy -= ( 1 << exp ) * ( CB_copy > 1 << exp );
}

Since loops are not supported, manual unwinding is essential, leading to 28 lines of code:

CB_copy = CB_seconds;
CB_half = 0;
CB_half += ( 1 << 12 ) * ( CB_copy > 1 << 13 );
CB_copy -= ( 1 << 13 ) * ( CB_copy > 1 << 13 );
CB_half += ( 1 << 11 ) * ( CB_copy > 1 << 12 );
CB_copy -= ( 1 << 12 ) * ( CB_copy > 1 << 12 );
. . .
CB_half += ( 1 << 1 ) * ( CB_copy > 1 << 2 );
CB_copy -= ( 1 << 2 ) * ( CB_copy > 1 << 2 );
CB_half += ( 1 << 0 ) * ( CB_copy > 1 << 1 );
CB_copy -= ( 1 << 1 ) * ( CB_copy > 1 << 1 );

In the absence of bit shifting, substitution with custom values from a plist is advised. Replace 1 << k with twoExp{k} for a set of k values in the plist:

CB_half += ( twoExp12 ) * ( CB_copy > twoExp13 );
CB_copy -= ( twoExp13 ) * ( CB_copy > twoExp13 );
etc

Lastly, convert the above into appropriate syntax:

%CB_copy = %id=CB_seconds% %
%CB_half = 0%
%CB_half = %( CB_half + %( twoExp12 * %( CB_copy > twoExp13 )% )% )% %
%CB_copy = %( CB_copy - %( twoExp13 * %( CB_copy > twoExp13 )% )% )% %
. . .
%CB_half = %( CB_half + %( twoExp0 * %( CB_copy > twoExp1 )% )% )% %
%CB_copy = %( CB_copy - %( twoExp1 * %( CB_copy > twoExp1 )% )% )% %

28 lines of code dedicated to halving a value. Best wishes.


Previous solution

Implementing GrimRepear1908's concept involves iterating up to 5000 and checking for the desired value through doubling. In a more conventional language, the logic appears as follows:

for repeatIndex in (0..5001):
  CB_half += repeatIndex*( repeatIndex*2==CB_seconds || repeatIndex*2==CB_seconds+1 )

For clarity within the API, keeping one operation per line is recommended, resulting in:

for repeatIndex in (0..5001):
  doubled = repeatIndex*2
  doubledLessOne = doubled-1
  CB_evenTarget = doubled==CB_seconds
  CB_oddTarget = doubledLessOne==CB_second
  isTarget = CB_evenTarget || CB_oddTarget // is 0 or 1
  multed = repeatIndex * isTarget
  CB_half = multed + CB_half

And in the specific syntax of the language, the code would be structured as follows:

%[repeat 5001]%
doubled = %( %id=repeatIndex% *2 )% %
doubledLessOne = %( %id=doubled% -1 )%
CB_evenTarget = %( %id=doubled% == %id=CB_seconds% )%
CB_oddTarget = %( %id=doubledLessOne% == %id=CB_second% )%
isTarget = %( %id=CB_evenTarget% || %id=CB_oddTarget% )%
multed = %( %id=repeatIndex% * %id=isTarget% )%
CB_half = %( %id=multed% + %id=CB_half% )%
%[endrepeat]%

Nuclearman's suggestion of a binary search method may offer brevity in the code, but considering the complexity involved in a simple loop, that approach is not currently explored.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Arranging an array of objects by a specific property in an Angular controller with the help of $filter

In my data set, there is an array of objects referred to as $scope.segments, which looks like this: [ { "_id": "55d1167655745c8d3679cdb5", "job_id": "55d0a6feab0332116d74b253", "status": "available", "sequence": 1, "body_original": " ...

Transferring Object Information from AJAX to PHP

When attempting to send data to a PHP file for database storage, I am not receiving any response. If a checkbox is checked, the [obj][idCheckbox] value is set to 1; otherwise, it is set to 0. This is the file responsible for sending the data: var i=0; v ...

Customize your select element's background using jQuery when the content changes

Here is a select element with different options to choose from: <select class="state"> <option value="1">Done</option> <option value="2">Closed</option> <option value="2">Open</option> <option v ...

What is a more efficient method for verifying the value of an object within an array that is nested within another object in JavaScript?

Is there a more efficient way to check for an object in an array based on a property, without having to go through multiple checks and avoiding potential errors with the ? operator? /** * An API returns a job object like: * { id: 123, name: 'The Job ...

What is the top JavaScript library for compressing and adding files for transfer to an API?

In the process of developing a Vue.js application, I am facing the task of zipping data into files, adding them to a zip folder, and then sending the zip folder to an API. After researching, I found two options - Zip and JSZip, but I'm uncertain about ...

Troubleshooting problems with local references in an Angular date picker

I am currently working with an Angular date picker component and trying to access its values using a local reference. Unfortunately, when I attempt to console log the local reference, it returns undefined. The datepicker, function, and trigger are provid ...

Is there a way to trigger a function after a tooltip or popover is generated using Twitter Bootstrap?

Is there a way to manipulate a tooltip or popover with twitter bootstrap after it has been created? It seems like there isn't a built-in method for this. $('#selector').popover({ placement: 'bottom' }); For instance, what if I ...

Pictures in Windows 7 have shifted to the left

After a recent migration to the Windows 7 operating system at my company, I encountered an issue. While using the same Visual Studio 2010 master file that was working fine on my Windows XP machine, I noticed that all the images below were now shifted to t ...

What is the method for obtaining the worldwide location of a vertex on a skinned mesh in Three.js?

In the realm of Three.js, we've recently acquired the ability to determine the global position of a vertex in a non-skinned mesh thanks to insights from this question. Now, the query arises - how can one ascertain the global position of a vertex in a ...

Establishing global date restrictions for the DatePicker component in Angular 8 using TypeScript across the entire application

I am currently learning Angular 8 and I am looking to globally set the minimum and maximum dates for a datepicker in my application. I would like to accomplish this by using format-datepicker.ts. Any suggestions on how I can achieve this? Min date: Jan 1, ...

Guide to retrieving objects in React.js

Struggling to extract a country from an online JSON file that I am currently fetching. I am attempting to streamline the process by creating a function to retrieve the country from the dataset and avoid repeating code. However, I am encountering difficulti ...

Adjust grid column sizes automatically when a smaller number is declared - tailwind

I am working with the tailwind grid system and have specified 6 columns for each row. However, if the number of elements is less than 6, I would like it to resize them to 3. <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 grid-flow-r ...

Content editable div causing overflow issues in Internet Explorer

I am having trouble with a content editable div where the text is not wrapping properly. I attempted to use "overflow:scroll" but it only ends up cutting off the text horizontally. https://i.stack.imgur.com/WlMdY.jpg ...

Steps to make ng-packagr detect a Typescript type definition

Ever since the upgrade to Typescript 4.4.2 (which was necessary for supporting Angular 13), it appears that the require syntax is no longer compatible. Now, it seems like I have to use this alternative syntax instead: import * as d3ContextMenu from ' ...

Utilizing jQuery Mobile - Dividing content across multiple HTML files

In the process of developing a web application utilizing jQuery and jQuery mobile, I am aiming to display various pages. Given that the corresponding html-markup may become lengthy, I am interested in dividing the html into separate files. For instance: & ...

React is giving me trouble as I try to map my tables. I am struggling to figure out how to do this

I have two .CSV files: "1.csv" and "2.csv". I need to display the data from each file in a table using the BootstrapTable component. My async functions, GetData(file) and FetchCSV(file), are working fine and providing the necessary array of objects for the ...

Do you need assistance with downloading files and disconnecting from clients?

When looking at the code snippet below: async function (req, res, next) { const fd = await fs.open("myfile.txt") fs.createReadStream(null, { fd, autoClose: false }) .on('error', next) .on('end', () => fs.close(fd)) . ...

Instructions on how to navigate to a class page by clicking a button in a ReactJS interface

I am currently working with React and have implemented 3 classes in separate files. The App.js file contains a navbar and button, which when clicked, displays a table from 'Table.js'. I have also added buttons in front of each row in the table th ...

Make toggleClass show up smoothly without disappearing

I'm currently working with jQuery's toggleClass() method and I want to achieve a fade-in effect without the corresponding fade-out animation. Using the "duration" attribute applies the same duration for both actions, which is not what I want. I w ...

How to line up two blocks side by side in a single block with Bootstrap without the use of CSS

The bootstrap margin is causing issues with this code <div class="row"> <div class="row1 col-lg-3"> <div class="row2 col-lg-1"></div> <div class="row2 col-lg-1"></di ...