I am trying to correctly print the values inside the array. The program is supposed to take only numbers that are 13 digits or higher. If I give n a number of 13 digits or 14 digits, the last position of the long array[8], which is array[7], gives random numbers such 4199280, or other 7 digit number. how can set array[7] to 0 then, so it doesn't hinder in my multiplication later. Can someone help me fix what I might be doing wrong without knowing? Thanks in advance.
#include <cs50.h>
#include <stdio.h>
#include <math.h>
long countDigit(long long n);
int main(void)
{
long n;
//This is asking for the input
do
{
n = get_long("Number: ");
}
while(!(countDigit(n)>12));
//Checksum math
long everyOther = 0;
long array[8];
int i = 0;
while(n > 0)
{
long lastNumber = n/10;
everyOther = lastNumber % 10;
n = n / 100;
printf("%li\n", everyOther);
array[i] = everyOther;
i++;
}
printf("\n");
printf("%li\n", array[0]);
printf("%li\n", array[1]);
printf("%li\n", array[2]);
printf("%li\n", array[3]);
printf("%li\n", array[4]);
printf("%li\n", array[5]);
printf("%li\n", array[6]);
printf("%li\n", array[7]);
printf("\n");
// long Multi = ((2*(array[0])) + (2*(array[1])) + (2*(array[2])) + (2*(array[3]))
// + (2*(array[4])) + (2*(array[5])) + (2*(array[6])) + (2*(array[7])));
// printf("%li\n", Multi);
}
//This function helps us with the counting of the number
long countDigit(long long n) {
return floor(log10(n) + 1);
}
To see what is happening more clearly, try adding a printf to the loop just before or after setting array[i]:
printf("array[%d] = %li\n", i, everyOther);
this will show you exactly which elements of the array get set, and what they get set to. You'll see, when the input is 13 or 14 digits, this will happen 7 times. For example, if your input is 1234567890123, you'll see
array[0] = 2
array[1] = 0
array[2] = 8
array[3] = 6
array[4] = 4
array[5] = 2
array[6] = 0
thus showing that you're only setting those 7 values of the array. So if you later try to print array[7], you'll get garbage; it has never been set to anything.
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.
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;
}
#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;
}
I am writing a program to see if a user entered number is Armstrong or not, here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int x = 0;
printf("Enter a natural number: ");
scanf("%d", &x);
int ans = x;
// Digit Counter
int counter = 0; //Variable for number of digits in the user entered number
int b = x; //For each time number can be divided by 10 and isnt 0
for (int i = 1; i <= x; i++){ // Then counter variable is incremented by 1
b /= 10;
if (b != 0){
counter += 1;
}
}
++counter;
//Digit Counter
int sum = 0;
// Digit Finder
int D;
for (int j = 1; j <= x; j++){
D = x % 10; //Shows remainder of number (last digit) when divided by 10
sum += pow(D, counter); //Raises Digit found by counter and adds to sum
printf("%d\n", sum);
x /= 10; // Divides user entered number by 10 to get rid of digit found
}
if (sum == ans){
printf("%d is a Armstrong number! :)", ans);
}else
printf("%d is not an Armstrong number :(", ans);
//Digit Finder
return 0;
}
My problem is that the program works fine apart from one point, when the program is given a Armstrong number which does not start with 1 then it behaves normally and indicates if it is an Armstrong number or not, but when i input a Armstrong number which start with 1 then it will print out the Armstrong number but -1.
For example: If i input something such as 371 which is an Armstrong number it will show that it is an Armstrong number. However if i input 1634 it will output 1633 which is 1 less than 1634.
How can i fix this problem?, also by the way could someone comment on my code and tell me if it seems good and professional/efficient because i am a beginner in C and would like someone else's opinion on my code.
How can I fix this problem.
You know the number of iterations you want to make once you have calculated the digit count. So instead of looping till you reach the value of x:
for (int j = 1; j <= x; j++){
use the digit counter instead:
for (int j = 1; j <= counter; j++) {
also by the way could someone comment on my code and tell me if it seems good and professional/efficient because i am a beginner in C and would like someone else's opinion on my code.
There's a number of things you can do to improve your code.
First and foremost, any piece of code should be properly indented and formatted. Right now your code has no indenting, which makes it more difficult to read and it just looks ugly in general. So, always indent your code properly. Use an IDE or a good text editor, it will help you.
Be consistent in your code style. If you are writing
if (some_cond) {
...
}
else
//do this
It is not consistent. Wrap the else in braces as well.
Always check the return value of a function you use, especially for scanf. It will save you from many bugs in the future.
if (scanf("%d", &x) == 1)
//...all OK...
else
// ...EOF or conversion failure...
exit(EXIT_FAILURE);
Your first for loop will iterate x times uselessly. You can stop when you know that you have hit 0:
for (int i = 1; i <= x; i++){ // Then counter variable is incremented by 1
b /= 10;
if (b == 0){
break;
}
counter += 1;
}
C has ++ operator. Use that instead of doing counter += 1
int D; you create this, but don't initialize it. Always initialize your variables as soon as possible
C has const qualifier keyword, which makes a value immutable. This makes your code more readable, as the reader can immediately tell that this value will not change. In your code, you can change ans variable and make it a const int because it never changes:
const int ans = x;
Use more descriptive names for your variables. ans, D don't tell me anything. Use proper names, so that the reader of your code can easily understand your code.
These are some of the things that in my opinion you should do and keep doing to improve your code and coding skills. I am sure there can be more things though. Keep your code readable and as simple as possible.
The condition in this loop
for (int i = 1; i <= x; i++){ // Then counter variable is incremented by 1
b /= 10;
if (b != 0){
counter += 1;
}
}
does not make sense because there will be numerous redundant iterations of the loop.
For example if x is equal to 153 that is contains only 3 digits the loop will iterate exactly 153 times.
Also additional increment of the variable counter after the loop
++counter;
makes the code logically inconsistent.
Instead of the loop you could write at least the following way
int counter = 0;
int b = x;
do
{
++counter;
} while ( b /= 10 );
This loop iterates exactly the number of times equal to the number of digits in a given number.
In this loop
for (int j = 1; j <= x; j++){
D = x % 10; //Shows remainder of number (last digit) when divided by 10
sum += pow(D, counter); //Raises Digit found by counter and adds to sum
printf("%d\n", sum);
x /= 10; // Divides user entered number by 10 to get rid of digit found
}
it seems you did not take into account that the variable x is decreased inside the body of the loop
x /= 10; // Divides user entered number by 10 to get rid of digit found
So the loop can interrupt its iterations too early. In any case the condition of the loop again does not make great sense the same way as the condition of the first loop and only adds a bug.
The type of used variables that store a given number should be unsigned integer type. Otherwise the user can enter a negative number.
You could write a separate function that checks whether a given number is an Armstrong number.
Here you are.
#include <stdio.h>
int is_armstrong( unsigned int x )
{
const unsigned int Base = 10;
size_t n = 0;
unsigned int tmp = x;
do
{
++n;
} while ( tmp /= Base );
unsigned int sum = 0;
tmp = x;
do
{
unsigned int digit = tmp % Base;
unsigned int power = digit;
for ( size_t i = 1; i < n; i++ ) power *= digit;
sum += power;
} while ( ( tmp /= Base ) != 0 && !( x < sum ) );
return tmp == 0 && x == sum;
}
int main(void)
{
unsigned int a[] =
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407,
1634, 8208, 9474, 54748, 92727, 93084, 548834
};
const size_t N = sizeof( a ) / sizeof( *a );
for ( size_t i = 0; i < N; i++ )
{
printf( "%u is %san Armstrong number.\n", a[i], is_armstrong( a[i] ) ? "": "not " );
}
return 0;
}
The program output is
0 is an Armstrong number.
1 is an Armstrong number.
2 is an Armstrong number.
3 is an Armstrong number.
4 is an Armstrong number.
5 is an Armstrong number.
6 is an Armstrong number.
7 is an Armstrong number.
8 is an Armstrong number.
9 is an Armstrong number.
153 is an Armstrong number.
370 is an Armstrong number.
371 is an Armstrong number.
407 is an Armstrong number.
1634 is an Armstrong number.
8208 is an Armstrong number.
9474 is an Armstrong number.
54748 is an Armstrong number.
92727 is an Armstrong number.
93084 is an Armstrong number.
548834 is an Armstrong number.
Please remove j++ from 2nd loop for (int j = 1; j <= x; j++)
I tried this:
void armstrong(int x)
{
// count digits
int counter = 0, temp = x, sum = 0;
while(temp != 0)
{
temp = temp/10;
++counter; // Note: pre increment faster
}
// printf("count %d\n",counter);
temp = x;
while(temp != 0)
{
sum += pow(temp % 10, counter);
temp = temp/10;
}
// printf("sum %d\n",sum);
if(x == sum)
{
printf("Armstrong\n");
}
else
{
printf("No Armstrong\n");
}
}
int main(){
armstrong(371);
armstrong(1634);
return 0;
}
Let's take this and add the ability to handle multiple numeric bases while we're at it. Why? BECAUSE WE CAN!!!! :-)
#include <stdio.h>
#include <math.h>
double log_base(int b, double n)
{
return log(n) / log((double)b);
}
int is_armstrong_number(int b, /* base */
int n)
{
int num_digits = trunc(log_base(b, (double)n)) + 1;
int sum = 0;
int remainder = n;
while(remainder > 0)
{
sum = sum + pow(remainder % b, num_digits);
remainder = (int) (remainder / b);
}
return sum == n;
}
int main()
{
printf("All the following are valid Armstrong numbers\n");
printf(" 407 base 10 - result = %d\n", is_armstrong_number(10, 407));
printf(" 0xEA1 base 16 - result = %d\n", is_armstrong_number(16, 0xEA1));
printf(" 371 base 10 - result = %d\n", is_armstrong_number(10, 371));
printf(" 1634 base 10 - result = %d\n", is_armstrong_number(10, 1634));
printf(" 0463 base 8 - result = %d\n", is_armstrong_number(8, 0463));
printf("All the following are NOT valid Armstrong numbers\n");
printf(" 123 base 10 - result = %d\n", is_armstrong_number(10, 123));
printf(" 0x2446 base 16 - result = %d\n", is_armstrong_number(16, 0x2446));
printf(" 022222 base 8 - result = %d\n", is_armstrong_number(8, 022222));
}
At the start of is_armstrong_number we compute the number of digits directly instead of looping through the number. We then loop through the digits of n in base b, summing up the value of the digit raised to the number of digits in the number, for the given numeric base. Once the remainder hits zero we know there are no more digits to compute and we return a flag indicating if the given number is an Armstrong number in the given base.
I continue my quest to store an input credit card number and validate it.
1) User types hipothetic credit card number, like 1234567898769999 (stored as string).
2) Convert string to an array of integers int digits[].
3) Multiply digitis in positions 1, 3, 5 ... last odd position by 2,
for instance 2*2, 2*4, 2*6, 2*8, 2*8, 2*6, 2*9, 2*9.
4) Store them in the same array and position [4,8,12,16,16, 12, 18,18].
5) Sum digits in positions 0, 2, 4 ... last even position.
Trying to run the code below with abnormal values appearing:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main (void) {
string cc_string;
printf("Please enter a credit card number:\n");
//Capture credit card number
cc_string = GetString();
// Array of integers for credit card digits int cc_digits[15];
int sum_evens, sum_odds = 0;
for (int i = 0; i < 16; i++)
{
cc_digits[i] = cc_string[i] - '0';
//Sum digits in even positions (0 ... 14)
if (i % 2 == 0)
{
sum_evens = sum_evens + cc_digits[i];
//Checking values
printf("cc_digits[%d] = %d; Sum_evens = %d\n", i, cc_digits[i], sum_evens);
}
else if (i % 2 == 1)
{
//Multiplies values in each position by 2 and stores in the same position
cc_digits[i] = 2 * cc_digits[i];
sum_odds = sum_odds + cc_digits[i];
//Checking values
printf("cc_digits[%d] = %d; Sum_odds = %d\n", i, cc_digits[i], sum_odds);
}
}
}
Will anybody have a clue about what is going on here?
It has been three days since I have tried to solve this.
Thanks in advance for the help.
abnormal values appearing
int sum_evens, sum_odds = 0;
Here you have not initialized the value of sum_evens, but you are using it further in your program this way in the if block of for loop:
sum_evens = sum_evens + cc_digits[i];
So, this results in undefined behaviour and thus abnormal values appear. To avoid this, try initializing sum_evens.
int sum_evens = 0, sum_odds = 0;