So you have to do:
11 = 1+1 = 2
3578 = 3+5+7+8 = 23 = 2+3 = 5
But the problem is that the number can be very large(consist of 10,000 digits)
#include <stdio.h>
#include <ctype.h>
int main(){
char buffer[100000];
scanf("%99999s", buffer);
unsigned long long int result = 0;
for( unsigned idx = 0; isdigit(buffer[idx]); idx++ ){
result = (int)buffer[idx] + result - '0';
}
int result2 = 0;
int digit = 0;
while ( result > 0 ){
digit = result % 10;
result2 += digit;
result = result / 10;
if( result <= 0 && result2 > 9){
result = result2;
result2 = 0;
continue;
}
}
printf("RESULT : %d\n",result2);
}
Input :
751681014401040450622780075254045270442210812770460775451184384531483702082226416361544531414410171607350014850333878358743220376871078174403200044662362218387877088216176613360252864405743551700372186186575780774423365770110772762276064451888336156654128153746808000717416854455788814078402738512314518407278677742343615032578760156411281210127537668157717015666162165516525027107402068668123177553108546580071328732081607873181528418805507115473871188671175418353685287375851146862706642660460660640361450625482328733578704685372147576117063756404450651264407575360484374363385487210664552841370274325526483461688624004361174850045865227812614165458631837856673343826214104801877607136035412561647757156215008153430481053606347145474412241557035145221136028312706780031881775353428185131338124663027888077214386322084144228202118607125173881566084750330384756507240153360252125102231317116187460551751644005660558858277077053174524651718580360376435305240031868065863876643181746460523888528353776530743505576145346723312843737184587288444786213277214628281832785420546274087146761566864614047504688123772643616870148637036486545882717162028017172706874088300344834424111884355042605060726257071061472334164583725618637172662277276238285574537252303708512187713753768210883717883214177506821154744051238430026270855363428730658126314153612053400077268874042185164222701426867051627554247573272557376740151571806220637182717476783435840540164172408587171868366825071315532702431761021552623061343345432712675051436011076617066231844451104348332548221106105114023473728208461760881801028437428634770630222621088305700346277351457830386857805275647013556147441362065165825384420633364237016227253566137375754313815436352300840071213800623627143462831576581300375511873047806550427070820275112032855056137212406102042344837643783510606621032343518643584052038422148828271478733221816003564556283801864300304433172707473414552811044246731560263787181360375220856023782825227102624663780175705186245881553055783106085313045005862533446468632134156855843085604348382611533515253722765723825136013746254432618268575605574880777370574873416807208456637441333184132067035322454017072312638668737073738377347585458061613007130848158715255752218380205816085742220815543528204180550315407345040343465616657842185850163106537650131781684036344622188084870842413154385436162802282440416080100438843655544106712445324162727681876878667304463852468413048081441201022820146183282812314331114888177386525521660163781083757743180378743438208686328556162024886323326120153038720833558641743826880113166153240558815120076524147752615042565452038541813882006275635438131506100314186187302343688270237767287844414752004085217272576403406754126201126712336183622843312501717384047822064857500303244180435065521612467421283018275707044616755208768040404760152323626173084386326286466747754211888301380460737572061342836367388845034654501045572058038063025335007602521812172166057474442286006578638145768783310135200717742254225860404885176720441047442166271805032286547386064076324568835101011406416753172855727057633455343825574000185777457428046681783622861257212832770071867083635215251007450841602618461842346412633483540142652201486041275081010667260201557331072426444618765328354076766417616130400424781247440566121265103547027280348113585104382410141813131455488838053702550808735183553830446408482367420076160076262663527670655562131264387255352825271342760566005822722332021348641167120856016554505570062536643673516223718301411084856100680157256766330732307710560350275148387768844636817022858087224581570845678335518432524511500037200041260067078007810158777163560526565081510773305010008850376420041473043255445606782654331804225784332044865574631035716102618467576882870067886585833110838276608241427536661612063618063214214585338564232814071202471515401656574782880713574621360444087084720607867137388445835311536257004364542878404634164452864246674118454286683235265786134857158678250347676325587704123207422854256630805386558578714726184126602861672885736446138500463533680748730338560546460428771824557181826464770402317772272740307477181478455585636075313283171573648400013054167571673116613571151510822374601535776316668534781321216853367674808200331442082688114414130302552638734526434061284204530625144825831481633217731670815133456452644081738063826088665353158124242484515531313451650213561416418085410405570606611140402142484384218384741442546410531674164472571000300215641678074334108435802784785688827488005837505826553888287125700643040881844334254155035271475167358430157130007013157486260051048760867051743488768342422141241284763218463632174454765861135173133286717111015542473116471513784372812532572507657618560461160572743554454317855102056287537832510205823506658075100270021761425488164177384714875436784437406006607216702405546421610285706140720336410004242104218828732364102102771261820130415166285786051016867117585071256587118755723107328726422080034138056203686821344515778507367155074361276125362022202351803832562288404317808420748687425723066470647261867532441741436340372734386377387536812712777758741523517725363013063628084148710814544350354128327450370108328345834184825032321204672125621760366274452185311667651381252480486872231627631122044224520137166555015885512810668513134734823527032322425078674033704700366250108836332352873123853430724168550066010372527701608883083567656658420863452247174555607068360358816616025006640012632030424828703053711305501480063563571055808404007667803548310285444582741013521587484871581873111322130771340805727521017815071546438331423181123825712415353283253055676286642757154578338046560888260426388261727558075655358131244258127644363553544161740513858558235265541018757524161706182667583126416834576488658808811147208535624307173833635764341270140176748648145554832612236561605878888234374007627452055011533720070776526077806626462013173033627356313122046445348831353878135766532587562735788641612802888058545633468326114560814135332856327735001740007712770551648528771444277478636812835258726114418280064621578160647816130504484417885455441310710237534854576868640827180867271531761050414728543450007823128426565157434460537338831685013827707746862257354742005884633255324034020140726006706533076110322584488787770046814060435340713051331121572716523741531875356702152315734851311371301664505011838574148782254327851402476184582057271422856838167763147707602848731788351754217448062810632163271832784804754855132333775805410764225072675773831382577208243836676513228533258804277348354423465462726763635586253784211383036438771457456004447381183528835587380018474478558760757488651234458158618285508566384516862071204682088461113757421315271543505317758616335700181150641341681041423844374066773814203773172040015357835077566066406714670073856536132620828836858568272876380471265510617104842623063547546011648218642120528241217201264418272541586085523518764050874346007711882466821876542475180688703464148317887712124820504824573450228111734537748838844660550575520873685472318251758020402465762411066627657844870521057325110206306425246704057182500708712735815425337147147484680845558170616553077740875373516455617458405322418668172025816470204565745732515143276215624473303535601018155746530745157426316131326448006255227746661304883216246242332321221046303207758322108418257570681028241142342484688526201382067331356726675158657337735228036833005140843574828268178828841221231212157311407301862716571557453483027852574588426386317222844845137486524171756112077772450745120438814043882721542500432780173282276283126542113737607746264233325574221587120848174301601886327120664423872308236666445766735274788115256514100204171708047626683537844852541635414486050687783225388745775154057484178630248743026361164786481223116305267273743145576636823725802764406413723436251762165820668803565807826085752366206338232114347130128821066058530265768254726576332032418730118514270183775054023384463034340706331703624150233863615660463048083263785543436400334336168067015171788458623687870730764865344561677627684365730626683072272624257375580502826520477760052580258620807556807623563026603046618634010113234004426635302058856310363212461781161353030781883726554753234473756114056038218043367517243478501237088565228021222257735670338820817870024347425161026158717204583758431002003234356520643035233555762368342114753878281652518156668068054210780825420587461040570476617171708256807440526301021557600786610784666273551445505075683164370060256603831838721252335608240674634433648778570417671457543258352862737344647424385202373703571366236526365774314152542608248523347802566388780166204546612148456535165672332228815853101305036068777746265720610677256370668701517100710332186638861005007310711864876551616102248756707824700427538726774173682441086323064411008186307371752102618060768502607627380178201343326340827013307717005315507127517241727734544314546316826358657803607532512068532335313084167267218766848485772658036626232251228241121145608623508757237303875624836550803486838238480781007152183824603204262111442105822411702738335005015331731517370266458832844686163274513052513143445663445645138422176610067282056232833531362883771248717505343234563001453584106746531048741017055621746366646150773232173061831068888866382201723777873735556684635566885100134773078406037346250430466763014315062572500326680833425582511220020804233713401314545117718084008434041613841270302837200388405753847723837030208332527585875058057764346701453767366355381480582356312063123418762453601741154336354218503285423233032455031888053657637446023116263037806702258215876864326411283205733020423242744783406845233527808618464288404304185036141087678562182326711378025403222216463781711163023683488586425024156028225301534471751801778118254806056605120208110044537253488272220720337416100518705316686511407527862467345875327140732360253782517501523302103632288166835628577115228462686218513817472506280223288028076843513285315285100421633053867834428803443
Output (need to be):
2
Output with my code:
4
So i don't know why is this happening because with another input my code is corrert:
763856354130136657360385516561520873045138714562332581204134142350730376283263680474653368757850487744860687174203110471643858602071801482028332653007166021826745174216138047817365348874514035821835612354050260544684725083051173324643825032336778782315104006603812742522771834088312702426100255155571471164588120604506466482133084060125572828026652740725300255036357264411565411313220610312477661525200624181273678765405170622003760807436012015546647124152462304506772560608127170466866433286314308076111732534314571162487345541117720317272124884630067232072656004285331281425165138177815136175542100311650333707342555832365361622315780463876462585205746384761118882137055072862101805442176434432204100601325362405055835148758015427383385114322832417385874425771288466408276226427662431076007266604531123285610451050580774714271542833845080001436232853660764311085680124630520500408800114274306755821766735740216024032300324714874556435420067888861610242771343152511705731160605244416176738413700221258437380040822775863133651778751211738450223765661576528804555312631150051080343763578868542634554368526333822067137015775230648240813186267232483470047125473601627341053116110277018577025244711848206154630086408583405243377832158881070838386616650275622740201355837112613225167544150076760876686687437824157810643238623035376176626013464366383165881501581054570782377367474818662273085618136500244702754070028836711466505422223042153582382870316175374820780744670187572281053042552333522136522460063685655230321850230236046606221767555035156666348610682685672858283014183766011436704361075434234124456752147833834811110648602534311607828673630167014010214853762411277664048424557438161681445011607235630404341508440814217855744175016074358350272755324876545487473277751734753378553246205084827232261611287686211273427857448171276116864645115258820041275040560465474772146438542184643252602451574158430138262022043256340221757528211417348241661373288441322588327746848234723120818482755778114478603430636437744812250072505662045741313625678162643547645055648750455875223558335531550864588817786283877062284676202818444760857748163561177317405675378462630271604223606503485528758641055610743733564552538477017350144102605615816482412455734188208707163860580652457783450451418444043300857505415584658811074731723222842772371678322840047352361531273433643063677401886518465376222687803576655160317208086728737014667870114387423180387477207077874548373254026433514131254778424332621000552175305788627840866162010103357607727137054058084747135075145827237602602550751458102011542757504244304754386465723634400852226538152618503058603500621173824642882510034110733072422021256507138673714786085262476240218077735880856236785561377704538477286631250223848718761345461341633752202643550117320307780533501404108507037045256817814285738880318564422836322713265887146816632472488385878560804805628138068502684877772080801570500632060020634751026342325005036165116407345860265756521710533601450110421412735046166370148372320354858855384455538852001200854374445327874810443614257318533171054717376752855102715544023273551280125152074823871037368145871374001111231535302078210687378318682248006648721508838864071270124521850040430463883400522814238655721532464053368042308325231264502030277332415144362510551004765254434777074016023140110854150705044415033281723875462545683042636672311863432500166770047028273032140573872737261673537040561630784337778887057476143740442084353580080833202125656344267723845416088835220820667515646872572420878775312107575745736146272106555521815846824608112642577763720502034022730453257700767811115641403014552686583713376027778256317227651825404567287218002523086080745584272785172566847107883166732360335523527877250520503320806348858606613416403242562868868134170620387153750184075382685277380050665544032023508256611047104277202414061004875626872732160248480317523135274231071317823157864623011663460074158680033502364232087046513751083468023635257267054650833816582473255018672115324373688885615605068683541222688784017610105573230674746308533031273056552814124513000128262665062473401424630217637373733542128236222257804358431140848385543085001375202038570856262101241050210166073055253710517487046547410034875606202033638552348687068545265511117105207778805460284233321584680215174150426461481553271732471124010254623404201610852756187412103672523365701581555125811711564383844225110016755403080612043706465700344618037232334153540453325620885466003424385252541244430370845172644232847213164075831524245134122266455733675014648015841781564665867644668464128116876118014752712750125224044762560738758328310758642000310784781871412172284242675178067541777245445383387540503251872434764770305821148084661630038185356686682318115573823042866403346053745751133568124186612871580883151360312847007008803227582374672743037340242823674407413056325542517185021134205620252366775208200064823886422241162006735853868638877477786133821115473824232201760731270667522850856055518462245543117045084503248851351452108403858241240224621533285056474050526630380275753318366727157450481516030125005682800758572356547247382376630120236285023834345010716080585807232401184404273432733020064278337065677335870205730243214740830572468815488584507137422201588308008353171531426283308866806800214083546628483757232554512231325824672637846146753563022676728575472630815131747862511186425175678413017284183600032377523161370615857228426216441670651321508540778103027285046137500830413281336378688114820684128521731657751518010707050357675552862833131164713006157316766532585147545848512145664466825384327114201113147776002142366261715863451642411525744443672043861217872570838088126424703842660226752806113251117174560238451758668525600210428466572842767316114440020052243554778737788862064663107527570807664170301178356786025037282065344006300066664078855573856763811061422417707587557008025483423025004343822287011234803822766765374540728128415248400366271010055714723674140588216153384530018863660481200376560286163083444238846821664406201226132183756850873446843773447472733335215077665786577138366650711538440337532564067211038513804671244304541677234642558862752687483668230813451713230581036554305487517305642341547002727358040231502322872466036573233112623747184701305147102242340461074000525773724681314444385142271831172242282106128821641837683156744828364377363647112668043105072583550110302186243342201435675863146700322312783245383428441532506357751768437250453722567858543037757436640236656643345041366240004761664022458120406517077383828555515000153123758160717474352831261322318407465420124722251650224571051741273403633434427121682671155580627438304044733286166144080510843443210434654852153834353525786424212843238703728783817615413783022718022432362430765676821417632134887667834006275050758051678025305467321844132606841363578310672834682561385251736043687764855173355035767050387255202262057625133562636500800240121100407874682380561057368140666210277655336057248825863816853341401220264668285354666623301326737711808416624103380865072285061540800005633578867821085625382440312055585737571655725738178626514523852136030086076157072710302437601326501508701758620334660245432543270717806880758034411561562683763163887446336155587384861156287657005734074003537654074653284110260676181325412877187528168734666271520607247252180017104088343324182851557471032677342316045738655470618385630116522627780047065281017556067817211275651457420636020808612820273002520306316580586080563558128188742642468043318336130005230352577058242045530768481747604750510611012867040057006446870051788848775665311374278206468757280320708011373885747120848724523673171436440851128532757420240160733240434548705141017533608143251516618205732658701660884504343748236136368085246867605563336508551825123428720853883252733510660325050747501432650003076323428318875525103123137434356727110647711414371827255332160338436255534510431314773718473508346410427014702423645426001156155752248331473813336752367720557038231407815643550056872830401101652154107574123642078818605184710045316822081026630451351732066087022272065254751131317405661547310056786746846138805221860542468231813626752864035880475085446870443858784613175522743543121844224315841131717275131238856855500178161846027605815001653207466463150131437845504411837324633271223806276775836788887173353821742663477644368547522322631308631772514256562461510534174204460016158764173520258202674655813114556774777078355684451231762538050158547751247183067326331384752282005087077028611333236448425020627810852875002736052467018877076654652044773518857242536841427776627164344008385638343411304537522710773676723586276747583433658501462382030027221083345253628151165017160233037611580364630320652162435871653288580314271676653333360626777270565650571515184520714711820167224423218144321611627733108670381586053634252733678450426382040428821735856374531350142554765486757543665158321821383007261711885375675137003616444706840667586544021222623471835765008507254778310230275088584303360822677281326766807302344883372153448072048810210605727424641014752681340304122862118000623188248154823000136522227277782380350202734473771163603184383400581232036372116046503128435120865347764426202814154301366768758374564643418344105136166728157437336147172848745260821852188351620243884055401284041761330855227177266661230258780126438676805778667471105134367300151724600360346203061353503721555243526536271404344130277330186810808260467582358267160641157658556842707151145157068340205342314861111447415621860400101265108166341806166531514636465602458287886752823638272116184053322180418851240228555056026770363502036664525266223086123266114873017123877345603775745244602252250408756513361778067548257582606543455888730834616705438377553157168523144160737216766065215775024027877561707416087530003045453326043720834644705333816324738254088141308802335013715806400077073757385261571831350365578855282768642663651711427602826446068482775202531175770641614332140381017487230605
Output:
1
Your if statement doesn't make sense to me, and your code needs nested loops. The outer loop should repeat until the number has been reduced to be in the 0 to 9 range, and the inner loop should iterate over each digit of the number, calculating the sum of the digits.
Here is my cleaned up and working version:
#include <stdio.h>
#include <stdint.h>
#include <ctype.h>
uint64_t sum_of_digits(uint64_t x) {
uint64_t sum = 0;
while (x > 0) {
sum += x % 10;
x /= 10;
}
return sum;
}
int main() {
uint64_t sum = 0;
while (1) {
int c = getchar();
if (!isdigit(c)) { break; }
sum += c - '0';
}
while (sum > 9) { sum = sum_of_digits(sum); }
printf("Result: %d\n", (int)sum);
}
Note: I tried to test this with your 9999-character input vectors but I am getting different results than what you claim is correct. I am getting 9 for the first one and 6 for the second one.
Update: A simpler way using math.
Let's think about what actually happens when you calculate this "digital root".
When you change 10 into 1, you are subtracting 9.
When you change 100 into 1, you are subtracting 99, which is a multiple of 9.
When you change 200 into 2, you are subtracting 2*99, which is still a multiple of 9.
When you change 3578 into 3+5+7+8, you are changing 3000 into 3 and 500 into 5 and 70 into 7, which means you are just subtracting 9 many times.
Everything that this program is supposed to do is just subtract 9 from the number as much as it can, until the number is in the 1 to 9 range. (This is not quite the same as x % 9, but pretty close.)
So we can simplify the program and make it much more efficient by taking advantage of this mathematical fact:
#include <stdio.h>
#include <ctype.h>
int main() {
unsigned int result = 0;
while (1) {
int c = getchar();
if (!isdigit(c)) { break; }
result += c - '0';
if (result > 9) { result -= 9; }
}
printf("Result: %u\n", result);
}
With this new program, I still get 9 and 6 as the answers for your large inputs.
There are multiple issues in your code:
you only allow for up to 99999 digits
you do not check for input failure: undefined behavior if redirected forom an empty file.
type unsigned long long is not required for result, long would suffice as 99999 * 9 is below 231-1.
for full portability, idx should have type size_t.
isdigit(buffer[idx]) has undefined behavior on platforms with signed char if the user typed non ASCII characters.
the first test case posted has 9999 digits and a digit root of 9, not 4 as you post, nor 2 as you expect. The second has a digit root of 6, not 1. There must be some mistake in the data.
Here is a much simpler solution:
#include <ctype.h>
#include <stdio.h>
int main() {
int c, result = 0;
while (isdigit(c = getchar()) {
if ((result += c - '0') > 9)
result -= 9;
}
printf("Result: %d\n", result);
return 0;
}
Related
The function should take the address of the integer and modify it by inserting zeros between its digits. For example:
insert_zeros(3) //3
insert_zeros(39) //309
insert_zeros(397) //30907
insert_zeros(3976) //3090706
insert_zeros(39765) //309070605
My code:
#include <stdio.h>
#include <math.h>
void insert_zeros(int* num);
int main() {
int num;
printf("Enter a number:");
scanf("%d", num);
insert_zeros(&num);
printf("Number after inserting zeros: %d", num);
return 0;
}
void insert_zeros(int* num){
int count = 0;
int tmp = *num;
//Count the number of digits in the number
while(tmp != 0){
tmp /= 10;
count++;
}
//calculating the coefficient by which I will divide the number to get its digits one by one
int divider = (int)pow(10, count-1);
int multiplier;
tmp = *num;
*num = 0;
/*
The point at which I'm stuck
Here I tried to calculate the degree for the number 10
(my thought process and calculations are provided below)
*/
(count >= 3)? count += (count/2): count;
//the main loop of assembling the required number
while (count >= 0){
multiplier = (int)pow(10, count); //calculating a multiplier
*num += (tmp / divider) * multiplier; //assembling the required number
tmp %= divider; //removing the first digit of the number
divider /= 10; //decreasing divider
count -= 2; //decreasing the counter,
//which is also a power of the multiplier (witch is 10)
}
}
My idea consists of the following formula:
For number "3" I shold get "30" and it will be:
30 = (3 * 10^1) - the power is a counter for number "3" that equals 1.
For number "39" it will be "309":
309 = (3 * 10^2) + (9 * 10^1)
For number "397" it will be "30907":
30907 = (3 * 10^4) + (9 * 10^2) + (7 * 10^0)
For number "3976" it will be "3090706":
3090706 = (3 * 10^6) + (9 * 10^4) + (7 * 10^2) + (6 * 10^0) - with each iteration power is decreasing by 2
For number "39765" it will be "309070605":
309070605 = (3 * 10^8) + (9 * 10^6) + (7 * 10^4) + (6 * 10^2) + (5 * 10^0)
And so on...
For a 3-digit number, the start power should be 4, for a 4-digit number power should be 6, for a 5-digit it should be 8, for 6-digit it should be 10, etc.
That algorithm works until it takes a 5-digit number. It outputs a number like "30907060" with an extra "0" at the end.
And the main problem is in that piece of code (count >= 3)? count += (count/2): count;, where I tried to calculate the right power for the first iterating through the loop. It should give the right number to which will be added all the following numbers. But it only works until it gets a 5-digit number.
To be honest, so far I don't really understand how it can be realized. I would be very grateful if someone could explain how this can be done.
As noted in comments, your use of scanf is incorrect. You need to pass a pointer as the second argument.
#include <stdio.h>
#include <math.h>
int main(void) {
int num;
scanf("%d", &num);
int num2 = 0;
int power = 0;
while (num > 0) {
num2 += (num % 10) * (int)pow(10, power);
num /= 10;
power += 2;
}
printf("%d\n", num2);
return 0;
}
There's an easy recursive formula for inserting zeros: IZ(n) = 100*IZ(n/10) + n%10.
That gives a very concise solution -- here the test cases are more code than the actual function itself.
#include <stdio.h>
#include <stdint.h>
uint64_t insert_zeros(uint64_t n) {
return n ? (100 * insert_zeros(n / 10) + n % 10) : 0;
}
int main(int argc, char **argv) {
int tc[] = {1, 12, 123, 9854, 12345, 123450};
for (int i = 0; i < sizeof(tc)/sizeof(*tc); i++) {
printf("%d -> %lu\n", tc[i], insert_zeros(tc[i]));
}
}
Output:
1 -> 1
12 -> 102
123 -> 10203
9854 -> 9080504
12345 -> 102030405
123450 -> 10203040500
Adapting some code just posted for another of these silly exercises:
int main() {
int v1 = 12345; // I don't like rekeying data. Here's the 'seed' value.
printf( "Using %d as input\n", v1 );
int stack[8] = { 0 }, spCnt = -1;
// Peel off each 'digit' right-to-left, pushing onto a stack
while( v1 )
stack[ ++spCnt ] = v1%10, v1 /= 10;
if( spCnt == 0 ) // Special case for single digit seed.
v1 = stack[ spCnt ] * 10;
else
// multiply value sofar by 100, and add next digit popped from stack.
while( spCnt >= 0 )
v1 = v1 * 100 + stack[ spCnt-- ];
printf( "%d\n", v1 );
return 0;
}
There's a ceiling to how big a decimal value can be stored in an int. If you want to start to play with strings of digits, that is another matter entirely.
EDIT: If this were in Java, this would be a solution, but the problem is in C, which I'm not sure if this can convert to C.
This may be a lot easier if you first convert the integer to a string, then use a for loop to add the zeros, then afterward reconvert to an integer. Example:
int insert_zeros(int num) {
String numString = Integer.toString(num);
String newString = "";
int numStringLength = numString.length();
for (int i = 0; i < numStringLength; i++) {
newString += numString[i];
// Only add a 0 if it's not the last digit (with exception of 1st digit)
if (i < numStringLength - 1 || i == 0) newString += '0';
}
return Integer.parseInt(newString);
}
I think this should give you your desired effect. It's been a little bit since I've worked with Java (I'm currently doing JavaScript), so I hope there's no syntax errors, but the logic should all be correct.
#include <stdio.h>
#include <math.h>
int main(){
int base5_v;
int digit = 0;
printf("> ");
scanf("%d", &base5_v);
int remainder = base5_v % 10;
base5_v /= 10;
int base10_v = remainder * (int) powf(5, digit++);
remainder = base5_v % 10;
base5_v /= 10;
base10_v += remainder * (int) powf(5, digit++);
remainder = base5_v % 10;
base10_v += remainder * (int) powf(5, digit++);
printf("%d in base 5 is %d in base 10\n", base5_v, base10_v);
return 0;
}
So I am having a hard time finding the issue in this code. the output is supposed to be like this after I input my number:
144 in base 5 is 49 in base 10
but when I compiled and ran the code it looked like this:
1 in base 5 is 49 in base 10
Can I get some help on what is wrong and how I can fix it?
Your code modifies base5_v each time it runs base5_v /= 10;.
In your example, you pass 144 as an input. The first time, it modified the value as 14 after the modulus operation, the second time 1 is left after modulus.
I think the biggest mistake in your code is not to use any loop. What'd happen if the user would enter 1234 or another digit length? There are many ways how you could have coded it, but this is one of them (ignoring the user input validation):
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#define MAX_DIGIT_LENGTH 10
int main()
{
char base5_v[MAX_DIGIT_LENGTH] = { '\0' };
printf("> ");
scanf("%s", base5_v);
int base10_v = 0;
int digit_length = (int)strlen(base5_v);
for (int digit = 0; digit < digit_length; digit++)
{
base10_v += pow(5, digit) * (base5_v[digit_length - digit - 1] - '0');
}
printf("%s in base 5 is %d in base 10\n", base5_v, base10_v);
return 0;
}
Input:
An input contains 2 integers A and B.
Output:
Print a wrong answer of A-B. Your answer must be a positive integer containing the same number of digits as the correct answer, and exactly one digit must differ from the correct answer. Leading zeros are not allowed. If there are multiple answers satisfying the above conditions, anyone will do.
Code:
#include <stdio.h>
int no_of_zeroes(int x);
int main()
{
int a, b;
int res1, res2;
int n1, n2;
scanf("%d",&a);
scanf("%d",&b);
res1 = a - b;
res2 = res1 + 10;
n1 = no_of_zeroes(res1);
n2 = no_of_zeroes(res2);
if(res1 < 9) printf("%d",res1 + 1);
else if(res1 == 9) printf("%d",res1-1);
else if((n1 == n2) && (res1 > 9)) printf("%d",res2);
else if((n2 > n1) && (res1>9))
{
res2 = res2 - 20;
printf("%d",res2);
}
}
int no_of_zeroes(int x)
{
int count = 0;
while(x>0)
{
x = x / 10;
count++;
}
return count;
}
Error:
What different should i do, basically else if blocks are creating trouble.
Your answer must be a positive integer containing the same number of digits as the correct answer
So the answer should be a-b. But the statement also says
exactly one digit must differ from the correct answer
Since it didn't specify the position of the digit, changing the last digit only should give us the correct answer to this problem. And so counting the number of digits of the difference is redundant.
Now the issue is - how to change the last digit? It's simple. We add 1 to the difference.
But there is a catch! If the difference is 99 and we add 1 to it, the result will be 100. Here, not only we're changing more than one digit, but also the number of digits.
And so, all we have to do is subtract 1 from the difference if the last digit of the difference is 9.
And so, the if-else block should look something like this:
int diff = a - b;
if(diff%10 == 9) {
diff--;
}
else {
diff++;
}
Here's my full code:
#include <stdio.h>
int main(void) {
int a, b;
scanf("%d%d", &a, &b);
int diff = a - b;
if(diff%10 == 9) {
diff--;
}
else {
diff++;
}
printf("%d\n", diff);
return 0;
}
On a different note, the function no_of_zeroes(int x) will return 0 if x=0. But, it should return 1 under general circumstances. And so the function should be something like this:
int no_of_digits(int x)
{
/* Adding the following line should fix the issue */
if(x==0) return 1;
int count = 0;
while(x>0)
{
x = x / 10;
count++;
}
return count;
}
I think you are making this much more complicated than needed. All you need is to check the last digit of the correct result and then change it.
For 0 and positive numbers:
last digit is 0 : add 1
last digit is 1 : add 1
...
last digit is 8 : add 1
last digit is 9 : subtract 1
For negative numbers, you simply change the sign and handle it as the positive number. This can be done because -123 has the same digits as 123.
So the code can be:
void wrongCalc(int a, int b)
{
int res = a - b; // Calculate result
if (res < 0) res = -res; // Change sign if negative
int lastDigit = res % 10; // Find last digit
if (lastDigit == 9)
{
--res; // Subtract 1
}
else
{
++res; // Add 1
}
printf("%d - %d = %d (correct result is %d)\n", a, b, res, a-b);
}
Limitations:
1) The program doesn't handle the possible integer overflow in a-b
2) The program doesn't handle the possible integer overflow in res = -res;
3) The program doesn't handle the case where the correct result is INT_MAX
I have a function that returns the length of a number by dividing it by 10 until it is less than 1 and greater than 0.
Ex.
12345 => 5
83 => 2
The issue is that 999999999999999s length should be 15 but my function returns 16. The function works fine for everything else...
Ex.
123456789123456 => 15
C code
#include <cs50.h>
#include <stdio.h>
int find_num_len(float num);
int counter = 0;
int main(void) {
long long int cc_num;
do {
cc_num = get_long_long("Number:");
}
while( cc_num < 0);
find_num_len(cc_num);
}
int find_num_len(float num) {
if (num > 0 && num < 1) {
printf("%i\n", counter);
return counter;
}
counter ++;
find_num_len(num/10);
return 0;
}
You're converting long long int to float unnecessarily. The mantissa of IEEE-754 32-bit float is 24 bits. And 2^24 = 16777216, which is the maximum possible number that can be represented with guaranteed precision.
This is one way to do it:
#include <stdio.h>
int find_num_len(long long int num) {
return num >= 10 ? 1 + find_num_len(num / 10) : 1;
}
int main(void) {
printf("%d\n", find_num_len(999999999999999));
return 0;
}
Or if you want to avoid the recursion:
int find_num_len(long long int num) {
int count = 1;
while (num >= 10) {
num = num / 10;
count++;
}
return count;
}
Probably a rounding error. The first integer that can’t be represented accurately by float is 2^24, approx 16 million which is way smaller than 15 9’s in a row.
Try using double which can go as high as 2^54; (from memory, best to check the ieee 754 spec to verify) which can represent Ints as high as ~1e16.
Or - compute the log10 of the number, add one, then truncate.
Len = floor (log10(number) + 1)
I need generate random 64-bit unsigned integers using C. I mean, the range should be 0 to 18446744073709551615. RAND_MAX is 1073741823.
I found some solutions in the links which might be possible duplicates but the answers mostly concatenates some rand() results or making some incremental arithmetic operations. So results are always 18 digits or 20 digits. I also want outcomes like 5, 11, 33387, not just 3771778641802345472.
By the way, I really don't have so much experience with the C but any approach, code samples and idea could be beneficial.
Concerning "So results are always 18 digits or 20 digits."
See #Thomas comment. If you generate random numbers long enough, code will create ones like 5, 11 and 33387. If code generates 1,000,000,000 numbers/second, it may take a year as very small numbers < 100,000 are so rare amongst all 64-bit numbers.
rand() simple returns random bits. A simplistic method pulls 1 bit at a time
uint64_t rand_uint64_slow(void) {
uint64_t r = 0;
for (int i=0; i<64; i++) {
r = r*2 + rand()%2;
}
return r;
}
Assuming RAND_MAX is some power of 2 - 1 as in OP's case 1073741823 == 0x3FFFFFFF, take advantage that 30 at least 15 bits are generated each time. The following code will call rand() 5 3 times - a tad wasteful. Instead bits shifted out could be saved for the next random number, but that brings in other issues. Leave that for another day.
uint64_t rand_uint64(void) {
uint64_t r = 0;
for (int i=0; i<64; i += 15 /*30*/) {
r = r*((uint64_t)RAND_MAX + 1) + rand();
}
return r;
}
A portable loop count method avoids the 15 /*30*/ - But see 2020 edit below.
#if RAND_MAX/256 >= 0xFFFFFFFFFFFFFF
#define LOOP_COUNT 1
#elif RAND_MAX/256 >= 0xFFFFFF
#define LOOP_COUNT 2
#elif RAND_MAX/256 >= 0x3FFFF
#define LOOP_COUNT 3
#elif RAND_MAX/256 >= 0x1FF
#define LOOP_COUNT 4
#else
#define LOOP_COUNT 5
#endif
uint64_t rand_uint64(void) {
uint64_t r = 0;
for (int i=LOOP_COUNT; i > 0; i--) {
r = r*(RAND_MAX + (uint64_t)1) + rand();
}
return r;
}
The autocorrelation effects commented here are caused by a weak rand(). C does not specify a particular method of random number generation. The above relies on rand() - or whatever base random function employed - being good.
If rand() is sub-par, then code should use other generators. Yet one can still use this approach to build up larger random numbers.
[Edit 2020]
Hallvard B. Furuseth provides as nice way to determine the number of bits in RAND_MAX when it is a Mersenne Number - a power of 2 minus 1.
#define IMAX_BITS(m) ((m)/((m)%255+1) / 255%255*8 + 7-86/((m)%255+12))
#define RAND_MAX_WIDTH IMAX_BITS(RAND_MAX)
_Static_assert((RAND_MAX & (RAND_MAX + 1u)) == 0, "RAND_MAX not a Mersenne number");
uint64_t rand64(void) {
uint64_t r = 0;
for (int i = 0; i < 64; i += RAND_MAX_WIDTH) {
r <<= RAND_MAX_WIDTH;
r ^= (unsigned) rand();
}
return r;
}
If you don't need cryptographically secure pseudo random numbers, I would suggest using MT19937-64. It is a 64 bit version of Mersenne Twister PRNG.
Please, do not combine rand() outputs and do not build upon other tricks. Use existing implementation:
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt64.html
Iff you have a sufficiently good source of random bytes (like, say, /dev/random or /dev/urandom on a linux machine), you can simply consume 8 bytes from that source and concatenate them. If they are independent and have a linear distribution, you're set.
If you don't, you MAY get away by doing the same, but there is likely to be some artefacts in your pseudo-random generator that gives a toe-hold for all sorts of hi-jinx.
Example code assuming we have an open binary FILE *source:
/* Implementation #1, slightly more elegant than looping yourself */
uint64_t 64bitrandom()
{
uint64_t rv;
size_t count;
do {
count = fread(&rv, sizeof(rv), 1, source);
} while (count != 1);
return rv;
}
/* Implementation #2 */
uint64_t 64bitrandom()
{
uint64_t rv = 0;
int c;
for (i=0; i < sizeof(rv); i++) {
do {
c = fgetc(source)
} while (c < 0);
rv = (rv << 8) | (c & 0xff);
}
return rv;
}
If you replace "read random bytes from a randomness device" with "get bytes from a function call", all you have to do is to adjust the shifts in method #2.
You're vastly more likely to get a "number with many digits" than one with "small number of digits" (of all the numbers between 0 and 2 ** 64, roughly 95% have 19 or more decimal digits, so really that is what you will mostly get.
If you are willing to use a repetitive pseudo random sequence and you can deal with a bunch of values that will never happen (like even numbers? ... don't use just the low bits), an LCG or MCG are simple solutions. Wikipedia: Linear congruential generator can get you started (there are several more types including the commonly used Wikipedia: Mersenne Twister). And this site can generate a couple prime numbers for the modulus and the multiplier below. (caveat: this sequence will be guessable and thus it is NOT secure)
#include <stdio.h>
#include <stdint.h>
uint64_t
mcg64(void)
{
static uint64_t i = 1;
return (i = (164603309694725029ull * i) % 14738995463583502973ull);
}
int
main(int ac, char * av[])
{
for (int i = 0; i < 10; i++)
printf("%016p\n", mcg64());
}
I have tried this code here and it seems to work fine there.
#include <time.h>
#include <stdlib.h>
#include <math.h>
int main(){
srand(time(NULL));
int a = rand();
int b = rand();
int c = rand();
int d = rand();
long e = (long)a*b;
e = abs(e);
long f = (long)c*d;
f = abs(f);
long long answer = (long long)e*f;
printf("value %lld",answer);
return 0;
}
I ran a few iterations and i get the following outputs :
value 1869044101095834648
value 2104046041914393000
value 1587782446298476296
value 604955295827516250
value 41152208336759610
value 57792837533816000
If you have 32 or 16-bit random value - generate 2 or 4 randoms and combine them to one 64-bit with << and |.
uint64_t rand_uint64(void) {
// Assuming RAND_MAX is 2^31.
uint64_t r = rand();
r = r<<30 | rand();
r = r<<30 | rand();
return r;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
unsigned long long int randomize(unsigned long long int uint_64);
int main(void)
{
srand(time(0));
unsigned long long int random_number = randomize(18446744073709551615);
printf("%llu\n",random_number);
random_number = randomize(123);
printf("%llu\n",random_number);
return 0;
}
unsigned long long int randomize(unsigned long long int uint_64)
{
char buffer[100] , data[100] , tmp[2];
//convert llu to string,store in buffer
sprintf(buffer, "%llu", uint_64);
//store buffer length
size_t len = strlen(buffer);
//x : store converted char to int, rand_num : random number , index of data array
int x , rand_num , index = 0;
//condition that prevents the program from generating number that is bigger input value
bool Condition = 0;
//iterate over buffer array
for( int n = 0 ; n < len ; n++ )
{
//store the first character of buffer
tmp[0] = buffer[n];
tmp[1] = '\0';
//convert it to integer,store in x
x = atoi(tmp);
if( n == 0 )
{
//if first iteration,rand_num must be less than or equal to x
rand_num = rand() % ( x + 1 );
//if generated random number does not equal to x,condition is true
if( rand_num != x )
Condition = 1;
//convert character that corrosponds to integer to integer and store it in data array;increment index
data[index] = rand_num + '0';
index++;
}
//if not first iteration,do the following
else
{
if( Condition )
{
rand_num = rand() % ( 10 );
data[index] = rand_num + '0';
index++;
}
else
{
rand_num = rand() % ( x + 1 );
if( rand_num != x )
Condition = 1;
data[index] = rand_num + '0';
index++;
}
}
}
data[index] = '\0';
char *ptr ;
//convert the data array to unsigned long long int
unsigned long long int ret = _strtoui64(data,&ptr,10);
return ret;
}