C program to find last three digits of a^b - dynamic-language-runtime

So, for small numbers my code does work, but it doesn't work for big numbers, for instance 100^10. So someone could help me finding my mistakes, or point out some clues for me to fix my code.
#include <stdio.h>
int main ( )
{
int n , exp , i;
char a[1000];
long long int value = 1 ;
scanf ( "%d %d" , & n , & exp ) ;
while ( exp --> 0 )
{
value *= n ;
}
if (value>999)
{
for (i=2; i>=0; i--)
{
a[i]=value%10;
value = value/10;
}
printf ("The last 3 numbers is %d%d%d.\n",a[0],a[1],a[2]);
}
else
printf ("The last 3 numbers is %d.\n", value);
return 0;
}

Related

argc = 1 always regardless of how many characters or words in a given sentence

I want to print argc to verify the words are being calculated correctly before moving to next section in my code. My code is:
int main(int argc, char *argv[])
{
string s = get_string("Text: ");
//Read letters;
n = strlen(s);
printf("%d\n", n);
printf("%d\n", argc);
Every time I run the program, argc = 1 always, even though the sentence typed has 4-5 words. I'm not sure why the program is not calculating argc correctly. Any help is greatly appreciated.
So you asked to read text from input and calculate letter & word count:
#include <stdio.h>
#include <ctype.h>
int main()
{
char a[1000] = {0};
//read a line from input
scanf("%[^\n]s", a);
int word_count = 0;
int letter_count = 0;
int idx = 0;
// go through the line
while (a[idx]){
//skip spaces
while(a[idx] && isspace(a[idx]))
idx++;
// if next char is a letter => we found a word
if (a[idx])
word_count++;
//skip the word, increment number of letters
while (a[idx] && !isspace(a[idx])){
letter_count++;
idx++;
}
}
printf("word count = %d letter count = %d", word_count, letter_count);
return 0;
}
EDIT : display line count also
#include <stdio.h>
#include <ctype.h>
int main()
{
char a[1000] = {0};
//read everyting from input until character '0' is found
scanf("%[^0]s", a);
int word_count = 0;
int letter_count = 0;
int sent_count = 0;
int idx = 0;
// go through the lines
while (a[idx]){
//skip spaces
//newline is also a space, check and increment counter if found
while(a[idx] && isspace(a[idx])){
if (a[idx] == '\n')
sent_count++;
idx++;
}
// if next char is a letter => we found a word
if (a[idx])
word_count++;
//skip the word, increment number of letters
while (a[idx] && !isspace(a[idx])){
letter_count++;
idx++;
}
}
printf("word count = %d letter count = %d line count = %d", word_count, letter_count, sent_count);
return 0;
}
Here's another way:
#include <stdio.h>
#include <string.h>
int main()
{
char a[1000] = {0};
int word_count = 0;
int letter_count = 0;
while (1){
scanf("%s", a);
// break when word starts with '0'
if (a[0] == '0')
break;
word_count++;
letter_count += strlen(a);
}
printf("word count = %d letter count = %d", word_count, letter_count);
return 0;
}
This way reads input until word starting with character '0' is found

Confusion about my QuickSort algorithm & Mergesort algorithm

I am currently conducting empirical studies to evaluate the run-time complexities of the quicksort, and mergesort algorithms. To do this I run a random number generator that stores whatever amount of numbers I specify in a binary file. The ranges of those numbers are from 1-1,000,000.I then run tests of each algorithm starting from 100,000 numbers, incrementing by 50,000 each time, until 1,000,000 numbers are sorted on the last run. So 20 tests each. I have successfully completed each algorithm but my results are kind of puzzingly. This is a graph showing my results.
I understand that quicksort has a worst case of O(n2) time, but typically O(n·lg(n)) time. Mergesort has Θ(n·lg(n)) time.
Also I would like to note that when I started the timer I just used clock() from time.h, and calculated the time elapsed. I started my timer one line of code before I called my sorting function.
What I dont understand is how my graph shows mergesort is always double the time, and reaching triple the time to sort numbers compared to quicksort.
My only thought is that for my mergesort algorithm every time I divide my array in half I use malloc to create a new integer array for each half. Of course this means a large amount of calls are made to malloc considering the number sizes I am sorting.
int* mergeSort(int* nums, int size){
int* left;
int* right;
int middle = size/2;
if(size <= 1)
return nums;
split(nums, size, &left, &right, middle);
//I dont understand why the code below wouldnt work in place of the split()
//when i run it, in main, nothing gets printed out. I guess i lose my pointer to the beginning of my array.
//left = nums;
//right = nums+middle;
left = mergeSort(left, middle);
right = mergeSort(right, size - middle);
merge(nums,left,right,middle,size - middle);
free(left);
free(right);
return nums;
}
void split(int* nums, int size, int** left, int** right, int middle){
int *lft = (int*) malloc ((sizeof(int) * middle));
int *rght = (int*) malloc ((sizeof(int) * size - middle));
int mid = middle;
int upMid = size - middle;
int i;
for(i=0; i < mid; i++)
lft[i] = nums[i];
for(i=0; i < upMid; i++)
rght[i] = nums[i+middle];
*left = lft;
*right = rght;
}
void merge(int* num, int* left, int* right, int sizeLeft, int sizeRight){
int i,j,k,n;
i=j=k=0;
n=sizeLeft + sizeRight;
while(k < n){
if(i< sizeLeft){
if(j<sizeRight){
insert(num,left,right,&i,&j,&k);
}
else{
append(num, left, sizeLeft, &i, &k);
}
}
else{
append(num,right,sizeRight,&j,&k);
}
}
}
void insert(int* num, int* left, int* right, int* i, int* j, int* k){
/*int i,j,k,n;*/
if(left[*i]<right[*j]){
num[*k] = left[*i];
(*i)++;
}
else{
num[*k] = right[*j];
(*j)++;
}
(*k)++;
}
void append(int* num, int* half, int sizeHalf, int* i, int* k){
while(*i < sizeHalf){
num[*k]= half[*i];
(*i)++; (*k)++;
}
}
I would greatly appreciate any feedback on this question of mine, and any advice on maybe making my mergesort function more efficient. Thanks!!
I have implemented a merge sort algorithm, you can have a look. I malloc a bak array at the beginning of mergeSort and every merge use the it afterwards.
#include <string>
#include <stdlib.h>
void _mergeSort(int *array, int *bakArray, int len) ;
void mergeSort(int *array, int len)
{
int *bak = (int *)malloc(sizeof(int)*len) ;
_mergeSort(array, bak, len) ;
free(bak) ;
}
void _mergeSort(int *array, int *bakArray, int len)
{
if (len >= 2) {
int leftLen = len/2 ;
_mergeSort(array, bakArray, leftLen) ;
_mergeSort(array+leftLen, bakArray, len-leftLen) ;
int *pa = array ;
int *pb = array+leftLen ;
int aIndex = 0 ;
int bIndex = 0 ;
while (aIndex < leftLen && bIndex < len-leftLen) {
int a = pa[aIndex] ;
int b = pb[bIndex] ;
if (a < b) {
bakArray[aIndex+bIndex] = a ;
++aIndex ;
} else if (a == b) {
bakArray[aIndex+bIndex] = a ;
bakArray[aIndex+bIndex+1] = a ;
++aIndex ;
++bIndex ;
} else {
bakArray[aIndex+bIndex] = b ;
++bIndex ;
}
}
if (aIndex < leftLen) {
memcpy(bakArray+aIndex+bIndex, pa+aIndex, sizeof(int)*(leftLen-aIndex)) ;
} else if (bIndex < len-leftLen) {
memcpy(bakArray+aIndex+bIndex, pb+bIndex, sizeof(int)*(len-leftLen-bIndex)) ;
}
memcpy(array, bakArray, sizeof(int)*len) ;
}
}
static const int MaxArraySize = 100 ;
int main()
{
srand(time(NULL)) ;
int array[MaxArraySize] ;
for (int i = 0 ; i < MaxArraySize; ++i) {
array[i] = rand() % 10000 ;
}
mergeSort(array, MaxArraySize) ;
for (int i = 0 ; i < MaxArraySize; ++i) {
printf("%d ", array[i]) ;
}
printf("\n") ;
return 0 ;
}

Prime number algorithm Objective C explanation please

Hi sorry for my bad english, i have a question guys, i'm learning objective c and i'm learning booleans right now, my question is: why when running the second loop in the code, the number 2 is taken as prime, i mean, as i see it p takes the value 2 in the first loop, then d start at 2 but then it says d < p, i think that's p-1 (2-1 = 1), so how that code works, it doesn't make sense, i understand why it works with any other number greater than 2 but i don't get it why it works with the number 2!
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
#autoreleasepool
{
int p, d;
BOOL isPrime;
for (p = 2; p <= 50; p++)
{
isPrime = true;
for (d = 2; d < p; d++)
{
if (p % d == 0)
isPrime = false;
}
if (isPrime == true)
NSLog(#"%i", p);
}
}
return 0;
}
The first loop starts p=2, then the inner loop take d=2 and then check if d<p. This condition is false because d=2 P=2. This means the first inner loop doesn't run and isPrime is always true at the first loop of p.
A prime number is divisible by 1 or itself.
So we check divisibility for all the numbers between 1 and the number.
That is why we start we 2 and till number-1
for(d = 2; d < p; d++ )
Prime numbers are the numbers which are not divisible by any other number.They are divisible by itself only (eg 2,3,5,7)
If we will only check till the half of number, since more than half of number will not divide it.
-(BOOL)checkNumberPrimeNumber:(int)number{
int i; BOOL flag=false;
for (i=2; i<number/2; i++) {
if (number%i==0) {
flag=true;
break;
}
}
if (flag==true) {
NSLog(#"%d is Not Prime Number",number);
}
else{
NSLog(#"%d is Prime Number",number);
}
return YES;
}

Bubble sort Descending and Ascending in C won't sort

I'm giving a user choices to whether sort the elements in ascending or descending order. I know my code can sorts the elements right but somewhere in main I think I'm making mistake in calling my function to print the ascending/descending element in their proper order. Or do I have to have another if statement like I have in the bubble_sort function? I need to make it so the Main function prints the final results to the user. Here's the output I'm getting:
Enter number of elements
3
Enter 3 integers
43
7
90
Enter sort order
Please enter A for ascending or D for descending order
d
Sorted list in descending order:
43
7
90
#include <stdio.h>
void bubble_sort(long [], char n);
int main()
{
long array[100], n, c;
printf("Enter number of elements\n");
scanf("%ld", &n);
printf("Enter %ld integers\n", n);
for (c = 0; c < n; c++)
scanf("%ld", &array[c]);
printf("Enter sort order\n");
fflush(stdin);
printf("Please enter A for ascending or D for descending order\n");
scanf("%ld", &n);
bubble_sort(array, n);
printf("Sorted list in descending order:\n");
for ( c = 0 ; c < n ; c++ )
{
printf("%ld\n", array[c]);
}
fflush(stdin);
getchar();
return 0;
}
void bubble_sort(long list[], char n)
{
long c, d, temp;
if(n=='a' || n=='A')
{
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (list[d] > list[d+1])
{
temp = list[d];
list[d] = list[d+1];
list[d+1] = temp;
}
}
}
}
if(n=='d' || n=='D')
{
long c, d, temp;
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d > n - c - 1; d++)
{
if (list[d] < list[d+1])
{/* Swapping */
temp = list[d];
list[d] = list[d+1];
list[d+1] = temp;
}
}
}
}
}
EDIT: Here I added a swap function just so the ascending/descending logic is more efficient. But I seem to mixed up use of the variables which I think is a big problem. Would anyone point out and help me understand where and why I'd need to use those variables? Thanks much!
#include <stdio.h>
void bubble_sort(int list[], int n, char c);
void swap(int x, int y, int array[]);
int main()
{
int array[100], j, i;
char c;
printf("Enter number of elements\n");
scanf("%d", &j);
printf("Enter %d integers\n", j);
for (i = 0; i < j; i++)
scanf("%d", &array[i]);
printf("Please enter A for ascending or D for descending order\n");
scanf("%s", &c);
bubble_sort(array, j, i);
printf("Sorted list in descending order:\n");
for (i = 0 ; i < j ; i++ )
{
printf("%d\n", array[i]);
}
getchar();
return 0;
}
void bubble_sort(int list[], int n, char c)
{
int i, j;
if(c=='a' || c=='A'){
for (i = 0; i < (n - 1); i++){
for (j = 0; j < (n - i) - 1; j++){
if (list[i] > list[j])
{
swap(i, j, list); }
}
}
}
if(c=='d' || c=='D') {
for (i = 0 ; i < ( n - 1 ); i++) {
for (j = 0 ; j > (n - i) - 1; j++) {
if (list[i] < list[j])
{
swap(i, j, list);
}
}
}
}
}
void swap(int x, int y, int array[])
{
int hold; //temp hold a number
hold = array[x];
array[x] = array[y];
array[y] = hold;
}
In this statements
printf("Please enter A for ascending or D for descending order\n");
scanf("%ld", &n);
you are overwritting the value stored in n that before these statements denoted the number of the elements in the array. You should declare one more variable of type char and use it for this code snippet.
Also the sort function should be declared as
void bubble_sort(long list[], int n, char c );
where n is the array size and c is either 'A' or 'D'
EDIT: Your new code contains many typos. Try the following
#include <stdio.h>
void swap( int x, int y, int array[] )
{
int hold; //temp hold a number
hold = array[x];
array[x] = array[y];
array[y] = hold;
}
void bubble_sort( int list[], int n, char c )
{
int i, j;
if ( c == 'a' || c == 'A' )
{
for ( i = 0; i < n - 1; i++ )
{
for ( j = 0; j < n - i - 1; j++ )
{
if ( list[j] > list[j+1] )
{
swap( j, j + 1, list);
}
}
}
}
if ( c=='d' || c=='D' )
{
for ( i = 0 ; i < n - 1; i++ )
{
for ( j = 0 ; j < n - i - 1; j++ )
{
if ( list[j] < list[j+1] )
{
swap( j, j + 1, list);
}
}
}
}
}
int main(void)
{
int array[100], j, i;
char c;
printf("Enter number of elements: ");
scanf( "%d", &j);
printf( "Enter %d integers\n", j );
for ( i = 0; i < j; i++ ) scanf( "%d", &array[i] );
printf("Please enter A for ascending or D for descending order: ");
scanf( " %c", &c );
printf( "%c\n", c );
bubble_sort( array, j, c );
printf( "Sorted list in the selected order:\n" );
for ( i = 0; i < j; i++ )
{
printf( "%d ", array[i] );
}
puts( "" );
return 0;
}

how to return longest words from an array?

given 2 arrays wrds[] , chars[] as an input to a function such that
wrds[] = [ "abc" , "baa" , "caan" , "an" , "banc" ]
chars[] = [ "a" , "a" , "n" , "c" , "b"]
Function should return the longest word from words[] which can be constructed from the chars in chars[] array.
for above example - "caan" , "banc" should be returned
Note: Once a character in chars[] array is used, it cant be used again.
eg: words[] = [ "aat" ]
characters[] = [ "a" , "t" ]
then word "aat" can't be constructed, since we've only 1 "a" in chars[].
There are kinds of anwers online but they are not written in Objective C.Can anyone help me solve this question in OC?
First, walk through the word array, one word at a time, throwing out all the words that can't be formed from the second array. To do that, for each word, walk through the characters of the word, throwing out that character from the second array. If we come to a character that's not in the second array, that word can't be formed from those characters.
Now we have an array consisting solely of the words that can be formed from those characters. Now sort that array by word length, longest first. Now start walking the array, looking at the length of each word. When that length value changes, stop; you have found all the longest words.
// Program do to do the same in C++
#include <iostream>
#include <string>
#include <map>
#include <vector>
using namespace std;
using std::vector;
vector<char*> match(char** words, int size, char* chars, map<char,int> &second)
{
vector<char*> res;
std::map<char,int> mapi = second;
int currsize = 0;
for(int i = 0; i < size ; i++){
char* wo;
wo = words[i];
int s= 0;
for( s=0; wo[s] != '\0'; s++){
}
if(s < currsize) {
//No need to iterate if already found a bigger word
//continue to see if the next word if bigger of the same size as currsize
continue;
}
// iterate through the map to see if all the letters present in the first array
bool found = true;
for(int j = 0; j <s ; j++){
map<char, int>::iterator it = mapi.find(wo[j]);
if(it == mapi.end()) {
found= false;
break;
}
}
if(!found) {
continue;
}
if(s > currsize) {
//remove the past res as found a bigger one
res.clear();
}
//Store this word in the vector as it is one of the biggest word so far
res.push_back(wo);
currsize = s;
}
return res;
}
int main()
{
map<char, int> leters;
char* words[5] = {"adc", "baa", "caan", "daanns", "banc"};
char ch1[]= {'a', 'a', 'n', 'c', 'b'};
int chsize = sizeof(ch1);
// put the ch1 chars in a map
for(int i = 0; i < chsize; i++) {
map<char,int>::iterator it =leters.find(ch1[i]);
if(it != leters.end()) {
it->second = it->second+1;
} else {
leters.insert(make_pair(ch1[i], 1));
}
}
char* chars = ch1;
vector<char*>v = match(words, 5, ch1, leters);
for(vector<char*>::iterator it = v.begin(); it != v.end(); it++) {
// it will print the result
cout << *it << endl;
}
return 0;
}