Dropping variable in lm formula still triggers contrast error
I'm trying to run lm() on only a subset of my data, and running into an issue.
dt = data.table(y = rnorm(100), x1 = rnorm(100), x2 = rnorm(100), x3 = as.factor(c(rep('men',50), rep('women',50)))) # sample data
lm( y ~ ., dt) # Use all x: Works
lm( y ~ ., dt[x3 == 'men']) # Use all x, limit to men: doesn't work (as expected)
The above doesn't work because the dataset now has only men, and we therefore can't include x3, the gender variable, into the model. BUT...
lm( y ~ . x3, dt[x3 == 'men']) # Exclude x3, limit to men: STILL doesn't work
lm( y ~ x1 + x2, dt[x3 == 'men']) # Exclude x3, with different notation: works great
This is an issue with the "minus sign" notation in the formula? Please advice. Note: Of course I can do it a different way; for example, I could exclude the variables prior to putting them into lm(). But I'm teaching a class on this stuff, and I don't want to confuse the students, having already told them they can exclude variable using a minus sign in the formula.
1 answer

The error you are getting is because x3 is in the model with only one value =
"men"
(see comment below from @Artem Sokolov)One way to solve it is to subset ahead of time:
dt = data.table(y = rnorm(100), x1 = rnorm(100), x2 = rnorm(100), x3 = as.factor(c(rep('men',50), rep('women',50)))) # sample data dmen<dt[x3 == 'men'] # create a new subsetted dataset with just men lm( y ~ ., dmen[,"x3"]) # now drop the x3 column from the dataset (just for the model)
Or you can do both in the same step:
lm( y ~ ., dt[x3 == 'men',"x3"])
See also questions close to this topic

How to get shaded confidence interval bands for glm coefficients?
I would like to plot the line and the shaded 95% confidence interval bands (for example using polygon)from a glm model (family binomial). For linear models (lm), I have previously been able to plot the confidence intervals from the predictions as they included the fit, lower and upper level see e.g. this answer How to plot regression transformed back on original scale with colored confidence interval bands? but I do not know how to do it here. Thanks for help in advance. You can find here the data that I used (it contains 3 variables and 4582 observations): https://drive.google.com/file/d/1RbaN2vvczG0eiiqnJOKKFZE9GX_ufl7d/view?usp=sharing Code and figure here:
# Models hotglm=glm(hotspot~age+I(age^2),data = data, family = "binomial") summary(hotglm) coldglm=glm(coldspot~age+I(age^2),data = data, family = "binomial") summary(coldglm) # Plot age = 1:200 lin=hotglm$coefficients[1]+hotglm$coefficients[2]*age+hotglm$coefficients[3]*age^2 pr = exp(lin)/(1+exp(lin)) par(mfrow=c(1,1)) plot(age, pr,type="l",col=2,lwd=2,ylim=c(0,.15)) lin=coldglm$coefficients[1]+coldglm$coefficients[2]*age+coldglm$coefficients[3]*age^2 pr = exp(lin)/(1+exp(lin)) lines(age, pr,type="l",col="blue", lwd=2)

Using a switch function in place of nested if functions
I'm new to R and I've been studying nested if functions. I did the following exercise from The Book of R to determine precise dosages for a drug. If there was any instance of "High" in
doselevel
I performed operations on the various doseslowdose
,meddose
,highdose
and returned a vector of the properdosage
. I have it working using nested if functions but it i've seen it alluded to that this is a situation that might be better suited for aswitch
function.What would the switch function for this situation look like?
lowdose < 12.5 meddose < 25.3 highdose < 58.1 doselevel < factor(c("Low","High","High","High","Low","Med","Med"),levels=c("Low","Med","High")) if(any(doselevel=="High")){ if(lowdose>=10){ lowdose < 10 } else { lowdose < lowdose / 2 } if(meddose>=26){ meddose < 26 } if(highdose>=60){ highdose < highdose * 1.5 } else { highdose < 60 } doseage < rep(lowdose,times=length(doselevel)) doseage[which(doselevel=="Med")] < meddose doseage[which(doselevel=="High")] < highdose } else { doselevel < factor(doselevel,c("Low","Med"),labels=c("Small","Large")) if((lowdose<15)&&(meddose<35)){ lowdose < lowdose * 1.5 meddose < meddose + highdose } }

Using values from slider in javascript DataTables calculations
I've got a nested
DataTable
in my shiny app that is made from the data below. There are two sliders that I have which make up a percentage of 100. If one slider is 50 the other sider is 50. These two numbers from the two sliders help make up theSpot:30(%)
and theSpot:15(%)
columns of the child table.There is another column,
Mix(%)
, where the user is able to go in and edit the numbers. When the user edits this column the numbers in theSpot:30(%)
and theSpot:15(%)
columns are suppose to be updated accordingly.The equations are:
Spot:30(%) = (Mix(%) * slider_value1)/100
Spot:15(%) = (Mix(%) * slider_value2)/100
Is there a way to use slider values from the Shiny app in the
JS callback
script to update theSpot:30(%)
and theSpot:15(%)
columns when theMix(%)
column is edited by the user??I've attempted to try a solution like this one, example1, as well as trying to follow this, communicating with shiny via javascript, but can't seem to wrap my head around this.
Data
Parent structure(list(Market = c("ABILENESWEETWATER", "ALBANYSCHENECTADYTROY, NY" ), `Gross CPP` = c("$0", "$0"), `Gross CPM` = c("$0", "$0"), `Historical Composite Gross CPP` = c("$0", "$0"), `Historical Composite Gross CPM` = c("$0", "$0")), .Names = c("Market", "Gross CPP", "Gross CPM", "Historical Composite Gross CPP", "Historical Composite Gross CPM"), row.names = c(NA, 2L), class = "data.frame") Child structure(list(Market = c("ABILENESWEETWATER", "ABILENESWEETWATER", "ABILENESWEETWATER", "ABILENESWEETWATER", "ABILENESWEETWATER", "ABILENESWEETWATER", "ABILENESWEETWATER", "ABILENESWEETWATER", "ABILENESWEETWATER", "ABILENESWEETWATER", "ALBANYSCHENECTADYTROY, NY", "ALBANYSCHENECTADYTROY, NY", "ALBANYSCHENECTADYTROY, NY", "ALBANYSCHENECTADYTROY, NY", "ALBANYSCHENECTADYTROY, NY", "ALBANYSCHENECTADYTROY, NY", "ALBANYSCHENECTADYTROY, NY", "ALBANYSCHENECTADYTROY, NY", "ALBANYSCHENECTADYTROY, NY", "ALBANYSCHENECTADYTROY, NY"), Daypart = c("Daytime", "Early Fringe", "Early Morning", "Early News", "Late Fringe", "Late News", "Prime Access", "Prime Time", "tv_2", "tv_cross_screen", "Daytime", "Early Fringe", "Early Morning", "Early News", "Late Fringe", "Late News", "Prime Access", "Prime Time", "tv_2", "tv_cross_screen"), `Mix (%)` = c(15, 10, 15, 10, 5, 5, 10, 10, 0, 0, 15, 10, 15, 10, 5, 5, 10, 10, 0, 0), `Spot:30 (%)` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), `Spot:15 (%)` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), `Gross CPP ($)` = c(18, 18, 16, 23, 24, 40, 26, 44, 0, 0, 77, 71, 61, 78, 109, 145, 93, 213, 0, 0), `Gross CPM ($)` = c(0, 0, 0, 0, 0, 0, 0, 0, 23, 13, 0, 0, 0, 0, 0, 0, 0, 0, 23, 13), `Historical Override CPP ($)` = c(18, 18, 16, 23, 24, 40, 26, 44, 0, 0, 77, 71, 61, 78, 109, 145, 93, 213, 0, 0), `Historical Override CPM ($)` = c(0, 0, 0, 0, 0, 0, 0, 0, 23, 13, 0, 0, 0, 0, 0, 0, 0, 0, 23, 13)), .Names = c("Market", "Daypart", "Mix (%)", "Spot:30 (%)", "Spot:15 (%)", "Gross CPP ($)", "Gross CPM ($)", "Historical Override CPP ($)", "Historical Override CPM ($)" ), class = "data.frame", row.names = c(NA, 20L))
EDIT
For some reason when I move the slider the Shiny Server observes the event and prints out the new slider value, but that new slider value doesn't get passed to the JS callback which in turn doesn't update the DataTable. The data table stays at the
var slider = 50
and doesn't update.Code
# The datatable callback parentRows < which(Dat[,1] != "") callback_js = JS( "var tv_spots30 = 50;", "Shiny.addCustomMessageHandler('sliderValue1', function(value1){", " tv_spots30 = value1;", " $('#' + children[0]).DataTable().draw()", " $('#' + children[1]).DataTable().draw();", "});", "var spots15 = 50;", "Shiny.addCustomMessageHandler('sliderValue2', function(value2){", " spots15 = value2;", " $('#' + children[0]).DataTable().draw();", " $('#' + children[1]).DataTable().draw();", "});", "function onUpdate(updatedCell, updatedRow, oldValue) {};", sprintf("var parentRows = [%s];", toString(parentRows1)), sprintf("var j0 = %d;", colIdx), "var nrows = table.rows().count();", "for(var i=0; i < nrows; ++i){", " if(parentRows.indexOf(i) > 1){", " table.cell(i,j0).nodes().to$().css({cursor: 'pointer'});", " }else{", " table.cell(i,j0).nodes().to$().removeClass('detailscontrol');", " }", "}", "", "// make the table header of the nested table", "var format = function(d, childId){", " if(d != null){", " var html = ", " '<table class=\"display compact hover\" ' + ", " 'style=\"paddingleft: 30px;\" id=\"' + childId + '\"><thead><tr>';", " for(var key in d[d.length1][0]){", " html += '<th>' + key + '</th>';", " }", " html += '</tr></thead><tfoot><tr>'", " for(var key in d[d.length1][0]){", " html += '<th></th>';", " }", " return html + '</tr></tfoot></table>';", " } else {", " return '';", " }", "};", "", "// row callback to style the rows of the child tables", "var rowCallback = function(row, dat, displayNum, index){", " if($(row).hasClass('odd')){", " $(row).css('backgroundcolor', 'white');", " $(row).hover(function(){", " $(this).css('backgroundcolor', 'lightgreen');", " }, function() {", " $(this).css('backgroundcolor', 'white');", " });", " } else {", " $(row).css('backgroundcolor', 'white');", " $(row).hover(function(){", " $(this).css('backgroundcolor', 'lightblue');", " }, function() {", " $(this).css('backgroundcolor', 'white');", " });", " }", "};", "", "// header callback to style the header of the child tables", "var headerCallback = function(thead, data, start, end, display){", " $('th', thead).css({", " 'bordertop': '3px solid green',", " 'color': 'black',", " 'backgroundcolor': 'white'", " });", "};", "", "// make the datatable", "var format_datatable = function(d, childId, rowIdx){", " // footer callback to display the totals", " // and update the parent row", " var footerCallback = function(tfoot, data, start, end, display){", " $('th', tfoot).css('backgroundcolor', '#F5F2F2');", " var api = this.api();", " var col_mix = api.column(2).data();", " for(let i = 0; i < col_mix.length; i++){", " api.cell(i,3).data(parseFloat(col_mix[i])*tv_spots30/100);", " api.cell(i,4).data(parseFloat(col_mix[i])*spots15/100);", " }", " api.columns().eq(0).each(function(index){", " if(index == 0) return $(api.column(index).footer()).html('Mix Total');", " var coldata = api.column(index).data();", " var total = coldata", " .reduce(function(a, b){return parseFloat(a) + parseFloat(b)}, 0);", " if(index == 3  index == 4 index == 5  index == 6  index==7  index==8) {", " $(api.column(index).footer()).html('');", " } else {", " $(api.column(index).footer()).html(total);", " }", " if(total == 100) {", " $(api.column(index).footer()).css({'color': 'green'});", " } else {", " $(api.column(index).footer()).css({'color': 'red'});", " }", " })", " // update the parent row", " var col_share = api.column(2).data();", " var col_CPP = api.column(5).data();", " var col_CPM = api.column(6).data();", " var col_Historical_CPP = api.column(7).data();", " var col_Historical_CPM = api.column(8).data();", " var CPP = 0, CPM = 0, Historical_CPP = 0, Historical_CPM = 0;", " for(var i = 0; i < col_share.length; i++){", " CPP += (parseFloat(col_share[i])*parseFloat(col_CPP[i]).toFixed(2));", " CPM += (parseFloat(col_share[i])*parseFloat(col_CPM[i]).toFixed(2));", " Historical_CPP += (parseFloat(col_share[i])*parseFloat(col_Historical_CPP[i]).toFixed(2));", " Historical_CPM += (parseFloat(col_share[i])*parseFloat(col_Historical_CPM[i]).toFixed(2));", " }", " table.cell(rowIdx, j0+2).data((CPP/100).toFixed(2));", " table.cell(rowIdx, j0+3).data((CPM/100).toFixed(2));", " table.cell(rowIdx, j0+4).data((Historical_CPP/100).toFixed(2));", " table.cell(rowIdx, j0+5).data((Historical_CPM/100).toFixed(2));", " }", " var dataset = [];", " var n = d.length  1;", " for(var i = 0; i < d[n].length; i++){", " var datarow = $.map(d[n][i], function (value, index) {", " return [value];", " });", " dataset.push(datarow);", " }", " var id = 'table#' + childId;", " if (Object.keys(d[n][0]).indexOf('_details') === 1) {", " var subtable = $(id).DataTable({", " 'data': dataset,", " 'autoWidth': true,", " 'deferRender': true,", " 'info': false,", " 'lengthChange': false,", " 'ordering': d[n].length > 1,", " 'order': [],", " 'paging': true,", " 'scrollX': false,", " 'scrollY': false,", " 'searching': false,", " 'sortClasses': false,", " 'pageLength': 50,", " 'rowCallback': rowCallback,", " 'headerCallback': headerCallback,", " 'footerCallback': footerCallback,", " 'columnDefs': [{targets: '_all', className: 'dtcenter'}]", " });", " } else {", " var subtable = $(id).DataTable({", " 'data': dataset,", " 'autoWidth': true,", " 'deferRender': true,", " 'info': false,", " 'lengthChange': false,", " 'ordering': d[n].length > 1,", " 'order': [],", " 'paging': true,", " 'scrollX': false,", " 'scrollY': false,", " 'searching': false,", " 'sortClasses': false,", " 'pageLength': 50,", " 'rowCallback': rowCallback,", " 'headerCallback': headerCallback,", " 'footerCallback': footerCallback,", " 'columnDefs': [", " {targets: 1, visible: false},", " {targets: 0, orderable: false, className: 'detailscontrol'},", " {targets: '_all', className: 'dtcenter'}", " ]", " }).column(0).nodes().to$().css({cursor: 'pointer'});", " }", " subtable.MakeCellsEditable({", " onUpdate: onUpdate,", " inputCss: 'myinputclass',", " columns: [2, 7, 8],", " confirmationButton: {", " confirmCss: 'myconfirmclass',", " cancelCss: 'mycancelclass'", " }", " });", "};", "", "// display the child table on click", "var children = [];", # array to store the id's of the already created child tables "table.on('click', 'td.detailscontrol', function(){", " var tbl = $(this).closest('table'),", " tblId = tbl.attr('id'),", " td = $(this),", " row = $(tbl).DataTable().row(td.closest('tr')),", " rowIdx = row.index();", " if(row.child.isShown()){", " row.child.hide();", " td.html('⊕');", " } else {", " var childId = tblId + 'child' + rowIdx;", " if(children.indexOf(childId) === 1){", # this child table has not been created yet " children.push(childId);", " row.child(format(row.data(), childId)).show();", " td.html('⊖');", " format_datatable(row.data(), childId, rowIdx);", " }else{", " row.child(true);", " td.html('⊖');", " }", " }", "});") # Module to create the nested structure of the table NestedData < function(dat, children){ stopifnot(length(children) == nrow(dat)) g < function(d){ if(is.data.frame(d)){ purrr::transpose(d) }else{ purrr::transpose(NestedData(d[[1]], children = d$children)) } } subdats < lapply(children, g) oplus < sapply(subdats, function(x) if(length(x)) "⊕" else "") cbind(" " = oplus, dat, "_details" = I(subdats), stringsAsFactors = FALSE) } # shiny # Bind the market level and mix breakout data together for the final table market_mix_table < reactive({ markets < market_costings_gross_net() mix_breakout < mix_breakout_digital_elements() # Make the dataframe # This must be met length(children) == nrow(dat) Dat < NestedData( dat = markets, children = split(mix_breakout, mix_breakout$Market) ) return(Dat) }) # Render the table output$daypartTable < DT::renderDataTable({ Server = FALSE # Whether to show row names (set TRUE or FALSE) rowNames < FALSE colIdx < as.integer(rowNames) # The data Dat < market_mix_table() # Table table < DT::datatable( Dat, callback = callback_js, rownames = rowNames, escape = colIdx1, style = "bootstrap4", options = list( lengthMenu = list( c(1, 10, 20), c("All", 10, 20) ), columnDefs = list( list(width = '30px'), list(width = '100px', targets = 1), list(visible = FALSE, targets = ncol(Dat)1+colIdx), list(orderable = FALSE, className = 'detailscontrol', targets = colIdx), list(className = "dtcenter", targets = "_all") ) ) ) # Some faancy Java magic path < getwd() # Call the html tools deps (js & css files in this directory) dep < htmltools::htmlDependency( "CellEdit", "1.0.19", path, script = "dataTables.cellEdit.js", stylesheet = "dataTables.cellEdit.css") table$dependencies < c(table$dependencies, list(dep)) # server = FALSE return(table) }) observeEvent(input[["tv_spots30"]], { print("30%") print(input[["tv_spots30"]]) session$sendCustomMessage("sliderValue1", input[["tv_spots30"]]) }) observeEvent(input[["spots15"]], { print("15%") print(input[["spots15"]]) session$sendCustomMessage("sliderValue2", input[["spots15"]]) }) # ui sliderInput("tv_spots30", "Spots 30 (%):", min = 0, max = 100, value = 50, step = 5 ), sliderInput("spots15", "Spots 15 (%):", min = 0, max = 100, value = 50, step = 5 ),

How to write a formula existing excel document with python
According to date in C column I will modify;
Week number in "whole" M column. I will use "=ISOWEEKNUM" as a excel formula.
Week day in "whole" N column. I will use "=WEEKDAY" as a excel formula.
xlsxwriter library is using to create excel file. But i will work on existing excel file. So I need to use openpyxl or another methods.
For trial, I created new excel file and tried openpyxl method but failed:
import openpyxl wb = openpyxl.load_workbook('D:\Documents\Desktop\deneme/formula.xlsx') ws=wb['Sheet1'] for i, cellObj in enumerate(ws['B'], 1): cellObj.value = '=ISOWEEKNUM(A1)'.format(i) wb.save('D:\Documents\Desktop\deneme/formula.xlsx')
I can see the formula but in excel #NAME error occurs. When I double click on #NAME error, and press Enter, formula works.
Do you have any suggestions on these codes or do you have any other methods?
Edit:
I succeed with below codes. But now i can't start from 2nd row in excel.
import openpyxl wb = openpyxl.load_workbook('D:\Documents\Desktop\deneme/formula.xlsx') ws=wb['Sheet1'] for i, cellObj in enumerate(ws['M'], 1): cellObj.value = '=_xlfn.ISOWEEKNUM(A2)'.format(i) wb.save('D:\Documents\Desktop\deneme/formula.xlsx')

How to write formula in excel using python
I want to write "ISOWEEKNUM" formula to "M column" according to date on "C column" using python. After that i will use this week number in my analyse.
I tried xlwt and xlsxwriter methods but couldn't succeed.
You can find xlsxwriter method, maybe I'm doing wrong.
https://xlsxwriter.readthedocs.io/working_with_formulas.html
Edit: I tried that one also;
Write formula to Excel with Python
Here is my trial;
import openpyxl wb = openpyxl.load_workbook('D:\Documents\Desktop\deneme/formula.xlsx') ws=wb['Sheet'] for i, cellObj in enumerate(ws['B'], 1): cellObj.value = '=ISOWEEKNUM(A1)'.format(i) wb.save('D:\Documents\Desktop\deneme/formula.xlsx')
It worked but now excel giving "#NAME" error.
When I double click on B2 column at press enter, I can see "9" number as a week number. I should solve it python, without any interference from excel.
Edit: Problem solved with jmcnamara's suggestion, but I want to apply this to whole M column.Which codes should I use?

c++ confusing formula for a random number between x and y
x + (rand() % y  x + 1)
this is a formula to find a random number between x and y but I don't know how it was made I want a logical/mathematical explanation for it and thank you in advance. 
Can I purge data from model objects in R?
I am estimating a large number of models (lmtype, but possibly others) in r. I do this ion a secure server, from which data export is restricted. I am allowed to export the results from models (coefficients, statistics) but not the individuallevel data.
I could prepare an object that only includes relevant statistics from the objects and export this. However, it would be very useful if I could export the model objects themselves without the data but at the same time retaining functionality to predict new data, tidy results with
broom
etc.I have tried to run, given m being an lmtype object:
m$model < NULL
but this does not let me use e.g.broom::confint_tidy afterwards
.Is there way possible to make my objects datafree and at the same time preserve functionality?

How to add regression equation to scatterplot in r
I am trying to make a basic scatterplot that displays the regression equation and r2 values in the top left of the plot panel. Below is the code to generate an initial figure with just the r2 value.
plot(OverlapInner$PR1Max, OverlapInner$PR4Max, ylim = c(23, 29), xlim = c(23, 29)) abline(a = 0, b = 1) fit < lm(PR1Max ~ PR4Max, data = OverlapInner) legend("topleft", bty = "n", legend = paste("R2:",format(summary(fit)$adj.r.squared, digits=4)))

When to run a multivariate logistic regression and how to interpret?
I have a df1:
Rate deaths_1000 MHI_2018 P_LessHSD P_BDorMore FPL AGE65_MORE 1 0.12589702 0 59338 11.3 27.7 236.4064 8653 2 0.08256048 0 57588 9.7 31.3 229.4343 44571 3 0.08928571 0 46064 16.8 11.5 183.5219 3690 4 0.08644537 0 50412 19.8 12.6 200.8446 10548 5 0.29591635 0 29267 24.8 13.3 116.6016 1661 6 0.05081301 0 37365 15.4 16.1 148.8645 3995
I have been running a multivariate linear model with
model < lm(Rate ~ FPL + P_LessHSD + AGE65_MORE, data = df1)
and been good results. I don't believe these have linear relationships though so now I want to do the multivariate logistic regression. I was wondering how this is done in R and how the coefficients are interpretted?When is a linear regression vs a multivariate regression better?

Collapsing multiple factor levels of (messy) character variable in R
I struggle to collapse multiple factor levels into only three factor levels of one specific variable in R Studio.
My point of departure is a
data.table
with 250 variables and roughly 4,000 rows. For one factor variable I want to collpase it's 75 levels into 3 levels. Moreover, of the 75 levels, 4 levels should be ignored (or set to NA before) since they include controversial information. This factor variable is based on survey answers that also include individual answers in text format. Sometimes even the language differs. So, it's a bit messy.I tried to collapse these 75 levels (or 71 levels if respective observations set to NA before) into 3 in two different ways. However, R always returns a
+
instead of a>
in the console and I can't continue to perform any other commands. Of course I can stop this by hittingEsc
but this does not help me receiving my desired result.So, this imaginary example should show what I tried:
1) using the
levels
andlist
functionslevels(dt$x) < list("No"=c("I don't allow anything", "..."), "Yes"= c("Number of visitors ,annual sales, sales growth, number of customers", "Net sales", "..."), "Maybe"=c("The CEO's approval is needed.", "To be discussed"))
2) using the
forcats
packagedt$x %>% fct_collapse(No= c("I don't allow anything", "..."), Yes= c("Number of visitors ,annual sales, sales growth", "number of customers", "Net sales", "..."), Maybe=c("The CEO's approval is needed.", "To be discussed"))
I assume the problem arises due to how the original variable is structured. Does anyone have an idea how I could address that?
A big thank you upfront!
Best, Ilka

CodeWars Sum By Factors C++ No idea how to make it work
I try to solve Sum by Factors on CodeWars and I have no idea how to get it working with C++.
My code prints just the highest prime factor for every number. A good solution is:
I = {12, 15}; // result = "(2 12)(3 27)(5 15)"
and mine is
Expected: equal to (2 12)(3 27)(5 15) Actual: (3 12)(3 27)(5 15)
Can anybody take a look at this code and help me find the correct solution?
I don't want to rewrite for instance Python code to Cpp, just trying to improve myself.
#include <string> #include <vector> #include <utility> #include <cmath> #include <numeric> class SumOfDivided { public: static std::string sumOfDivided(std::vector<int> &lst) { std::vector<std::pair<int, int>> v; std::string rtn = ""; int sum = std::accumulate(lst.begin(), lst.end(), 0); v.emplace_back(std::make_pair(primeFactors(std::ref(sum)), std::ref(sum))); for(auto& elem : lst) v.emplace_back(std::make_pair(primeFactors(std::ref(elem)), std::ref(elem))); sort(v.begin(), v.end()); for(auto& elem : v) rtn += "(" + std::to_string(elem.first) + " " + std::to_string(elem.second) + ")"; return rtn; } static int primeFactors(int& n) { int helper = 2; int number = abs(n); while(number > helper) if(number % helper == 0) { number /= helper; helper = 2; } else helper++; return helper; } };

Find all possible factors A and B that product to C efficiently
Given a natural number C, what is an efficient way to compute all possible positive factors A and B where AB = C in C++?
I have implemented the following solution, however, I am wondering if there are any more optimal methods to achieve this.
for(int A = 1; A <= C; A++) { if(C%A) continue; int B = C/A; cout << A << " times " << B << " equals " << C << endl; }
Note: A and B are allowed to be swapped (ex: A=2, B=3 and B=3, A=2 are both valid where C=6).