Maximum possible sum of N digits from range of N Random numbers in Turbo C++.
//Big Numbers from Random input.
#include<iostream.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
#include<conio.h>
unsigned long digitSum(long);
int main()
{
char *num,ch,str[20];
int n, i, j, k, pos,size;
long sum=0, lsum=0, x;
time_t t;
clrscr();
cout<<"================================================================\n";
cout<<" MAXIMUM SUM OF N DIGITS FROM RANGE OF N RANDOM NUMBERS.\n";
cout<<"================================================================\n";
cout<<"Enter Length of Random Numbers : ";
cin>>n;
cout<<"Enter Sum of Digits you want : ";
cin>>size;
srand((unsigned) time(&t));
for(i=0;i<n;i++)
{
ch=(rand()%10)+48;
num[i]=ch;
}
num[i]='\0';
for(i=0;i<n-size+1;i++)
{
sum=0;
for(j=0,k=i;j<size;j++)
{
str[j]=num[k++];
}
x=atol(str);
sum=digitSum(x);
if(sum>=lsum)
{
lsum=sum;
pos=i;
}
}
cout<<"\nRandomly generated "<<n<<" number string is:\n\n";
for(i=0;i<n;i++)
{
if(i>=pos && i<pos+size)
{
textbackground(5);
textcolor(10);
cprintf("%c",num[i]);
textcolor(7);
textbackground(0);
}
else
cout<<num[i];
}
cout<<"\n\nThe Largest Sum of "<<size<<" digits is : "
<<lsum<<" from index no. : "<<pos<<" to "<<pos+size-1<<endl;
cout<<"================================================================\n";
getch();
return 0;
}
unsigned long digitSum(long n)
{
unsigned long temp, s=0;
while(n!=0)
{
temp=n%10;
s+=temp;
n/=10;
}
return s;
}
#include<iostream.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
#include<conio.h>
unsigned long digitSum(long);
int main()
{
char *num,ch,str[20];
int n, i, j, k, pos,size;
long sum=0, lsum=0, x;
time_t t;
clrscr();
cout<<"================================================================\n";
cout<<" MAXIMUM SUM OF N DIGITS FROM RANGE OF N RANDOM NUMBERS.\n";
cout<<"================================================================\n";
cout<<"Enter Length of Random Numbers : ";
cin>>n;
cout<<"Enter Sum of Digits you want : ";
cin>>size;
srand((unsigned) time(&t));
for(i=0;i<n;i++)
{
ch=(rand()%10)+48;
num[i]=ch;
}
num[i]='\0';
for(i=0;i<n-size+1;i++)
{
sum=0;
for(j=0,k=i;j<size;j++)
{
str[j]=num[k++];
}
x=atol(str);
sum=digitSum(x);
if(sum>=lsum)
{
lsum=sum;
pos=i;
}
}
cout<<"\nRandomly generated "<<n<<" number string is:\n\n";
for(i=0;i<n;i++)
{
if(i>=pos && i<pos+size)
{
textbackground(5);
textcolor(10);
cprintf("%c",num[i]);
textcolor(7);
textbackground(0);
}
else
cout<<num[i];
}
cout<<"\n\nThe Largest Sum of "<<size<<" digits is : "
<<lsum<<" from index no. : "<<pos<<" to "<<pos+size-1<<endl;
cout<<"================================================================\n";
getch();
return 0;
}
unsigned long digitSum(long n)
{
unsigned long temp, s=0;
while(n!=0)
{
temp=n%10;
s+=temp;
n/=10;
}
return s;
}
No comments
Post your comments