Generating random integer values within a range in C [duplicate] - c

This question already has answers here:
How to generate a random integer number from within a range
(11 answers)
Closed 9 years ago.
How do I go about generating random integer values between a range (in this case 1-12 including 1 and 12) in the C language?
I've read about seeding (srand()) and using rand() within a range but am unsure about how to go about it.
Edit: Here is what I have so far
# include <stdio.h>
# include <stdlib.h>
# include <time.h>
// Craps Program
// Written by Kane Charles
// Lab 2 - Task 2
// 7 or 11 indicates instant win
// 2, 3 or 12 indicates instant los
// 4, 5, 6, 8, 9, 10 on first roll becomes "the point"
// keep rolling dice until either 7 or "the point is rolled"
// if "the point" is rolled the player wins
// if 7 is rolled then the player loses
int wins = 0, losses = 0;
int r, i;
int N = 1, M = 12;
int randomgenerator();
main(void){
/* initialize random seed: */
srand (time(NULL));
/* generate random number 10,000 times: */
for(i=0; i < 10000 ; i++){
int r = randomgenerator();
if (r = 7 || 11) {
wins++;
}
else if (r = 2 || 3 || 12) {
losses++;
}
else if (r = 4 || 5 || 6 || 8 || 9 || 10) {
int point = r;
int temproll;
do
{
int temproll = randomgenerator();
}while (temproll != 7 || point);
if (temproll = 7) {
losses++;
}
else if (temproll = point) {
wins++;
}
}
}
printf("Wins\n");
printf("%lf",&wins);
printf("\nLosses\n");
printf("%lf",&losses);
}
int randomgenerator(){
r = M + rand() / (RAND_MAX / (N - M + 1) + 1);
return r;
}

The simple way is
#include <stdlib.h>
#include <sys/time.h>
int main(void)
{
struct timeval t1;
gettimeofday(&t1, NULL);
srand(t1.tv_usec * t1.tv_sec);
int a = 1, b = 12;
int val = a + (b-a) * (double)rand() / (double)RAND_MAX + 0.5;
return 0;
}
Edit, since someone asked: You really do have to use floating point arithmetic to get this to come out right (or as right as it can given rand()'s limitations such as they are). Any solution which relies purely on integer arithmetic and rand() will of necessity use \ or %, and when this happens you will get roundoff error--where c and d are declared int and c = 5 and d = 2, for example, c/d == 2 and d/c == 0. When comes to sampling from a range, what happens is that in compressing the range [0, RAND_MAX] to [a, b], you have to do some kind of division operation since the former is so much larger than the latter. Then roundoff creates bias (unless you get really lucky and things evenly divide). Not a truly thorough explanation but I hope that conveys the idea.

You should use: M + rand() / (RAND_MAX / (N - M + 1) + 1)
Don't use rand() % N (which tries to return numbers from 0 to N-1). It is poor, because the low-order bits of many random number generators are distressingly non-random. (See question 13.18.)
Example code:
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main ()
{
int r, i;
int M = 1,
N = 12;
/* initialize random seed: */
srand (time(NULL));
/* generate number between 1 and 12: */
for(i=0; i < 10 ; i++){
r = M + rand() / (RAND_MAX / (N - M + 1) + 1);
printf("\n%d", r);
}
printf("\n") ;
return EXIT_SUCCESS;
}
It's working here at codepad.

Related

A function that takes an integer and inserts zeros between its digits

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.

Digital Root in c

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;
}

Why my area problem is giving wrong answer?

I am learning c. So, I was practicing in a online judge. I have got a logic behind the problem and submitted ans got wrong answer. What is the problem?
Problem:
Area
100 Points · Limits 1s, 512 MB
In this problem, you will be given a square which has a length of n. Co-ordinates of the square are (0,0), (n,0),(n,n),(0,n) . You need to draw 4 straight lines:
Line from (0,1) to (n,n-1)
Line from (1,0) to (n-1,n)
Line from (0,n-1) to (n,1)
Line from (1,n) to (n-1,0)
These four lines will intersect in a point (x,y) like the figure shown below.
Calculate the total area of A+B+C+D (except the four corner unit square).
Input
Input will start with an integer T. Then there will be T cases. Each case will contain one integer N. 1 <= T <= 100000
3 <= n <= 1018
Output
For each test case, print “Case x: y” without quotation marks where x is the case number and y is the required answer.
It is guaranteed that y is always an integer.
Sample
Input Output
1
6
Case 1: 8
My code:
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
int main()
{
int test, i;
scanf("%d", &test);
for(i=0; i<test; i++)
{
double n, area, a,x, b1, b, s, tri, area1, area_t;
scanf("%lf", &n);
area= n*n;
a=n-2;
x=n/2;
b1= (x-1)*(x-1) + x*x;
b= sqrt(b1);
s= (a+b+b)/2;
area1= s*(s-a)*(s-b)*(s-b);
area_t = (4* sqrt(area1));
printf("Case %d: %.0lf\n",i+1, (area-(area_t + 4)));
}
return 0;
}
Please help me to improve the code. Thank you.
I believe you have a compatability problem and your online judge is on a C89 implementation where "%lf" does not exist, making your program output
Case 1: %.0lf
Case 2: %.0lf
...
Try using the C89 specifier
printf("Case %d: %.0f\n", i + 1, area - (area_t + 4));
/* ^^^^ C89, not %.0lf */
Note: double x; scanf("&lf", &x) has been valid since C89.
Let Area be the requested area, which can be calculated as:
Area = OuterSquareArea - 4 * IsoscelesTringleArea - 4 * SmallSqareArea
where:
OuterSqareArea = n * n
IsoscelesTriangleArea = base * height / 2
= (n - 2) * (n / 2) / 2
= (n - 2) * n / 4
SmallSquareArea = 1 * 1
= 1
The computation of Area can be summed up to:
Area = (n * n) - 4 * ((n - 2) * n / 4) - 4 * (1)
= n * n - (n - 2) * n - 4
= (n - (n - 2)) * n - 4
= 2 * n - 4
The trace guarantees that t, n and Area are integers. The code we need is then:
#include <stdio.h>
int main() {
int i, t, n;
scanf("%d", &t); /* read t */
for (i = 1; i <= t; i++) { /* for any i in [1,t] */
scanf("%d", &n); /* read n */
printf("Case %d: %d\n", i, 2 * n - 4); /* solve */
}
}
The code could simply be extented to check t and n to be in the given ranges.

How to generate 12 digit random number in C?

I'm trying to generate 12 digit random numbers in C, but it's always generating 10 digit numbers.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void main()
{
srand(time(NULL));
long r = rand();
r = r*100;
printf("%ld",r);
}
rand() returns an int value in the range of [0...RAND_MAX]
Based on the C spec, RAND_MAX >= 32767 and RAND_MAX <= INT_MAX.
Call rand() multiple times to create a wide value
unsigned long long rand_atleast12digit(void) {
unsigned long long r = rand();
#if RAND_MAX >= 999999999999
#elif RAND_MAX >= 999999
r *= RAND_MAX + 1ull;
r += rand();
#else
r *= RAND_MAX + 1ull;
r += rand();
r *= RAND_MAX + 1ull;
r += rand();
#endif
return r;
}
The above returns a number if the range of 0 to at least 999,999,999,999. To reduce that to only that range, code could use return r % 1000000000000;.
Using % likely does not create an balanced distribution of random numbers. Other posts address details of how to cope with that like this good one incorporated as follows.
#if RAND_MAX >= 999999999999
#define R12DIGIT_DIVISOR (RAND_MAX/1000000000000)
#elif RAND_MAX >= 999999
#define RAND_MAX_P1 (RAND_MAX+1LLU)
#define R12DIGIT_DIVISOR ((RAND_MAX_P1*RAND_MAX_P1-1)/1000000000000)
#else
#define RAND_MAX_P1 (RAND_MAX+1LLU)
#define R12DIGIT_DIVISOR ((RAND_MAX_P1*RAND_MAX_P1*RAND_MAX_P1-1)/1000000000000)
#endif
unsigned long long rand_12digit(void) {
unsigned long long retval;
do {
retval = rand_atleast12digit() / R12DIGIT_DIVISOR;
} while (retval == 1000000000000);
return retval;
}
Note that the quality of rand() is not well defined, so repeated calls may not provide high quality results.
OP's code fails if long is 32-bit as it lacks range for a 12 decimal digit values. #Michael Walz
If long is wide enough, *100 will always make the least 2 decimal digits 00 - not very random. #Alexei Levenkov
long r = rand();
r = r*100;
The result of rand is int, which means you can't get a 12 digit number directly from it.
If you need value that is always 12 digits you need to make sure values fit in particular range.
Sample below assumes that you need just some of the numbers to be 12 digits - you just need 8 extra bits - so shifting and OR'ing results would produce number in 0x7fffffffff-0 range that would often result up to 12 digit output when printed as decimal:
r = rand();
r = (r << 8) | rand();
PS: Make sure the variable that will store the result is big enough to store the 12 digit number.
My simple way to generate random strings or numbers is :
static char *ws_generate_token(size_t length) {
static char charset[] = "1234567890"; // generate numbers only
//static char charset[] = "abcdefghijklmnopqrstuvwxyz1234567890"; to generate random string
char *randomString = NULL;
if (length) {
randomString = malloc(sizeof(char) * (length + 1));
if (randomString) {
for (int n = 0; n < length; n++) {
int key = rand() % (int)(sizeof(charset) -1);
randomString[n] = charset[key];
}
randomString[length] = '\0';
}
}
return randomString;
}
Explain the code
Create an array of chars which will contains (numbers, alphabets ...etc)
Generate a random number between [0, array length], let's name it X.
Get the character at random X position in the array of chars.
finally, add this character to the sequence of strings (or numbers) you want to have in return.
How to use it ?
#define TOKEN_LENGTH 12
char *token;
token = ws_generate_token(TOKEN_LENGTH);
conversion from string to int
int token_int = atol(token);
dont forget !
free(token); // free the memory when you finish
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, n;
time_t t;
n = 5;
/* Intializes random number generator int range */
srand((unsigned) time(&t));
/* Print 5 random numbers from 50 to back
for( i = 0 ; i < n ; i++ )
{
printf("%d\n", rand() % 50);
}
return(0);
}

How to solve infinite loop for generated music?

I have a program that I want to create a randomly generated bar of music (4 beats to a bar, using C Major scale). However, I'm having trouble understanding the math and keep overflowing my do while loop, creating more than 4 notes to the bar which I want to avoid.
I am using aServe, which was created by my tutor, but basically opens a stream to an Oscillator that plays the arguments I've commented.
/* Program for randomly written bar of 4/4 in C Major */
#include "aservelibs/aservelib.h"
#include <stdio.h>
#include <stdlib.h>
//macros
#define SEMIBREVE (1.0)
#define MINIM (1.0/2)
#define CROTCHET (1.0/4)
#define QUAVER (1.0/8)
#define SEMIQUAVER (1.0/16)
#define DEMISEMIQUAVER (1.0/32)
#define C (261.63)
#define D (293.66)
#define E (329.63)
#define F (349.23)
#define G (391.99)
#define A (440.00)
#define B (493.88)
int millisec(int bpm, double note) {
return (int)(
60 /* seconds */
* 1000 /* milliseconds per second */
* 4 /* crotchets per semibreve */
* note
/ bpm
);
}
int main()
{
int bpm = 120; //BPM Value
double Length[] = {SEMIBREVE, MINIM, CROTCHET, QUAVER, SEMIQUAVER, DEMISEMIQUAVER}; //Array of Note Lengths
double Pitch[] = {C, D, E,F, G, A, B}; //Array of CMajor Scale Freq
int randLength = (rand() % 6); //random positions for note length
int randPitch = ( rand() % 7); //random positions for note pitch
double barTotal = 0; //amount of bar currently completed
do {
if(barTotal < 1) //if bar total is smaller than 1
{
barTotal = Length[randLength] + barTotal; //add note to total
aserveOscillator(0, Pitch[randPitch], 1, 2); //Starts stream to oscialltor
//aserveOscillator(Index,Frequency,Amplitude,WaveType);
aserveSleep(millisec(bpm, Length[randLength])); //play the notes for the length of time specified in milliseconds
randLength = (rand() % 6); //prepare next random note
randPitch = (rand() % 7); //prepare next random pitch
//Output
printf("Note: ");
printf("%lf", Pitch[randPitch]);
printf("\n For: ");
printf("%lf", Length[millisec(bpm,randLength)]);
printf("\n With Bar Total: ");
printf("%lf", barTotal);
printf("\n\n");
}
else
{
if(barTotal != 1) //if bar total is bigger than 4
{
randLength = (rand() % 6); //try another number
}
}
} while (barTotal != 1); //will stop once reaches 4
return 0;
}
Consider thinking about the problem differently. Think of a bar as "n" slots where n is the most granular note type you have. So in your case a bar is a group of 32 slots. Rather than representing your numbers as fractions, use integral types to show how many of those "slots" each takes. So a DEMISEMIQUAVER takes 1 slot, which can be represented as an int rather than being (1.0 / 32.0) which introduces some potentially ugly issues.
Once you do this the solution is more straightforward:
1) How many slots are left in the current bar?
2) Choose a random note from a pool of notes smaller than the remaining slots
3) Recalculate how much room is left after adding the new note
4) If the remaining room is zero, proceed to the next bar.
Below is your code, adapted to this new approach. Not fully tested but it should avoid most if not all of the pitfalls discussed thus far.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//macros
#define SEMIBREVE (32)
#define MINIM (16)
#define CROTCHET (8)
#define QUAVER (4)
#define SEMIQUAVER (2)
#define DEMISEMIQUAVER (1)
#define C (261.63)
#define D (293.66)
#define E (329.63)
#define F (349.23)
#define G (391.99)
#define A (440.00)
#define B (493.88)
int GetMaxIndex(int remainingLength)
{
// Returns the largest upper bound of the Length array that
// should be considered based on how much room remains in
// the current bar.
int result;
if(remainingLength == 32) result = 5;
if(remainingLength < 32) result = 4;
if(remainingLength < 16) result = 3;
if(remainingLength < 8) result = 2;
if(remainingLength < 4) result = 1;
if(remainingLength < 2) result = 0;
return result;
}
int main()
{
double Pitch[] = {C, D, E,F, G, A, B}; //Array of CMajor Scale Freq
int bpm = 120; //BPM Value
int Length[] = {DEMISEMIQUAVER, SEMIQUAVER, QUAVER, CROTCHET, MINIM, SEMIBREVE}; //Array of Note Lengths
char* Labels[] = {"DEMISEMIQUAVER (Thirty Second)", "SEMIQUAVER (Sixteenth)", "QUAVER (Eighth)", "CROTCHET (Quarter)", "MINIM (Half)", "SEMIBREVE (Whole)"};
int remainingThisBar;
int barsToGenerate = 4;
int randLength = (rand() % 6); //random positions for note length
int randPitch; //random positions for note pitch
int maxIndex;
int randIndex;
srand(time(NULL));
for(int barNumber = 0; barNumber < barsToGenerate; barNumber++)
{
printf("Beginning bar: %i\n", barNumber);
remainingThisBar = 32;
while(remainingThisBar > 0)
{
maxIndex = GetMaxIndex(remainingThisBar); // What is the biggest note index we still have room for?
randIndex = maxIndex == 0 ? 0 : (rand() % maxIndex); // Get a random note between 0 and maxIndex
randPitch = ( rand() % 7); // Random positions for note pitch
randLength = Length[randIndex]; // Length in 32nds
remainingThisBar -= randLength;
// Output
printf("\tNote: %s # %f\n", Labels[randIndex], Pitch[randPitch]);
printf("\t32nds remaining in bar: %i\n", remainingThisBar);
printf("\n");
/* TODO - Output note via aServe*/
}
}
}

Resources