Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
have to reverse number and get difference between normal and reverse number.
The input consists of N numbers, where N is an arbitrary positive integer. The first line of the input
contains only a positive integer N. Then follows one or more lines with the N numbers; these numbers
should all be non-negative and may be single or multiple digits. These are the original numbers you need
to generate their N corresponding magic numbers.
i was thinking maybe using a while loop and just doing one input at a time, anyone have any thoughts?
what i have so far
#include <stdio.h>
int reverseInteger();
int generateMagicNumber();
int main()
{
int n,i;
char all;
printf("How many magic numbers do you want");
scanf("%d",&n);
while (i<n){ //
while (n != 0) //reversing number
{
rev = rev * 10;
rev = rev + n%10;
n = n/10;
i++;
all = n;
}
}
}
Assignment 1:
Reverse Number Magic Sequence
Due: Wednesday January 27, 2016 11:59pm EST
A reverse number is a number written in arabic numerals, but where the
order of digits is reversed. The first digit becomes the last and vice
versa. For example, the number 1245 when its digits are reversed it
would become 5421. Note that all the leading zeros are omitted. That
means if the number ends with a zero, the zero is lost by reversing
(e.g. 1200 gives 21). Also note that the reversed number never has any
trailing zeros. Finally, every single digit number (i.e. 0-9) is its
own reverse number. In order to generate a magic number, we reverse a
given original number and store the absolute value of the difference
between the original number and its reversed version. For example,
given the number 476, we will generate the reverse number 674 and then
compute the absolute value of the difference between 476 and 674 to be
198. We then reverse 198 to display the number 891; we call that the magic number!
We need your help to compute the magic numbers of a given sequence.
Your task is to calculate the difference between a given number and
its reverse version, and output the reverse of the difference. Of
course, the result is not unique because any particular number is a
reversed form of several numbers (e.g. 21 could be 12, 120 or 1200
before reversing). Thus we must assume that no zeros were lost by
reversing (e.g. assume that the original number was 12).
Input
The
input consists of N numbers, where N is an arbitrary positive integer.
The first line of the input contains only a positive integer N. Then
follows one or more lines with the N numbers; these numbers should all
be non-negative and may be single or multiple digits. These are the
original numbers you need to generate their N corresponding magic
numbers.
Output
For each original number in the sequence, print
exactly one integer – its magic number. Omit any leading zeros in the
output. On a separate line, output the largest absolute difference
encountered in the sequence. Sample Input
6
24 1 4358 754 305 794
Sample Output
81 0 6714 792 891 792
4176
Specific Requirements: [15 pts]
[ 3 pts] Write a function called reverseInteger, that takes as input an unsigned integer and returns its reversed digits version as an
unsigned integer.
[ 3 pts] Write a function called generateMagicNumber, that takes as input an unsigned integer and return its magic number as described in
the problem.
[ 3 pts] Display the sequence of magic numbers correctly. (shown in the script file)
[ 2 pts] Display the largest absolute difference (shown in the script file)
[ 3 pts] Demonstrate the complete program using a main function capable of processing the input of any sequence and producing its
corresponding output.
[ 1 pt] Compilation on the CS server gcc compiler without errors and warnings.
Failure to properly document your entire code will receive a mark of
zero.
You are to submit the following:
Source code file: assign1.c
Script file demonstrating the compilation and execution : assign1.txt
To generate the script file use the following command from the CS
server:
cp assign1.c assign1.backup
typescript assign1.txt
cc assign1.c
a.out
[test your code here with at least 3 different input test cases in addition to the example given]
exit
[These steps will create a file called assign1.txt. Do not edit its contents - just submit it!]
Hint: This table explains the work done in this example:
Originalnumber
Reverse Absolute difference
Reverse (Magic number)
X Xr |X-Xr| |X-Xr|r
24 42 18 81
1 1 0 0
4358 8534 4176 6714
754 457 297 792
305 503 198 891
794 497 297 792
Note that your program should not use arrays and should be able to
read a sequence of N size, for any value of N (a 32 bit integer). Of
course, memory space optimization should be considered since there is
no need to store all the N numbers in memory all at once at any given
time.
You should read a new number in each iteration of the while loop:
#include <stdio.h>
int reverseInteger();
int generateMagicNumber();
int main() {
int n, i;
char all;
printf("How many magic numbers do you want");
if (scanf("%d", &n) != 1)
return 1;
for (i = 0; i < n; i++) {
int num, temp, rev, magic;
if (scanf("%d", &num) != 1)
return 2;
rev = 0;
temp = num;
while (temp != 0) { //reversing number
rev = rev * 10;
rev = rev + temp % 10;
temp = temp / 10;
}
if (rev < num)
magic = num - rev;
else
magic = rev - num;
printf("%d ", magic);
}
printf("\n");
return 0;
}
If you enter all the numbers on one line, the answers will appear on a single line below it.
Related
I am confused how to find out how many times a number has been repeated in a user input. I am able to input numbers and see which numbers are repeating but am unsure of how to print out each inputed number and how many times that number was used. This is what I have so far
#include <stdio.h>
#include <stdlib.h>
int main(){
double numArray[100];
int x = 0;
int y = 0;
int counter = 1;
int count = 0;
setvbuf(stdout, NULL, _IONBF, 0);
printf("Enter any number of integers between 0 and 99 followed a non-numeric: \n");
for (x = 0; x < 100; x++) {
if (scanf("%lf", &numArray[x]) != 1)
break;
counter = counter + 1;
}
counter = counter - 1;
for(x = 0; x < counter; x++){
for(y = x + 1; y < counter; y++){
if(numArray[x] == numArray[y]){
printf("duplicate found: %lf\n", numArray[x]);
break;
}
}
}
return EXIT_SUCCESS;
}
Continuing for my initial comment, whenever you want to capture the frequency of values within a range, you generally want to declare an array and let each element of the array represent one value within the range. (this applies to integer input). For example, in your case, if you want to find the frequency of the integer values entered by a user in the range of 0-99, you would declare an array with 100 elements (representing values 0-99) and initialize all values to 0.[1]
Then each time the user enters a valid value in the range, you increment that element. For example, if your user enters 58, you would increment array[58] = array[58] + 1; (or simply array[58]++;). The value of array[58] is now 1 indicating the user has entered 58 once. (if 58 was entered again, it would be 2, and so on...)
This lends itself nicely for your input loop. You simply declare say int x; and in your scanf call, you fill x, validate it is within the range and then array[x]++; For example with your numarray declared as int [100], you could do [2]:
#define NMAX 100 /* define constants, avoid 'magic' numbers in code */
...
for (;;) { /* loop until non-numeric encountered */
int x;
if (scanf("%d", &x) != 1) /* check for non-numeric */
break;
if (x < 0 || x >= NMAX) { /* validate value in range */
fprintf (stderr, "error: value outside of range -- "
"try again.\n");
continue; /* if out of range - get new number */
}
numarray[x]++; /* increment frequency at element x */
}
Now in your case the 0-99 exactly matches the zero-based array indexing used in C, but you can index any range simply by adjusting the indexes. For example, if you were interested in a range of 50-150 you would simply adjust the indexes as required (e.g. numarray[x-50]++;)
However, in your code, it is quite unclear what your actual intent is. For instance you ask for values between 0-99, but then declare numarray as a floating-point type. If your intent was to have the user enter whole number values, then your array type should be an integer type instead. That reduces to the classic frequency problem which you could handle simply in a manner similar to the following:
#include <stdio.h>
#include <stdlib.h>
#define NMAX 100 /* define constants, avoid 'magic' numbers in code */
int main (void){
int i, numarray[NMAX] = {0}; /* C favors all lower-case over
* camelCase variable names */
printf ("Enter any number of integers between 0 and 99 "
"followed a non-numeric: \n");
for (;;) { /* loop until non-numeric encountered */
int x;
if (scanf("%d", &x) != 1) /* check for non-numeric */
break;
if (x < 0 || x >= NMAX) { /* validate value in range */
fprintf (stderr, "error: value outside of range -- "
"try again.\n");
continue; /* if out of range - get new number */
}
numarray[x]++; /* increment frequency at element x */
}
for (i = 0; i < NMAX; i++) /* output frequency of values */
printf (" %2d : %d times\n", i, numarray[i]);
return EXIT_SUCCESS;
}
Example Use/Output
For example, you can generate 500 values between 0-99 and output the frequency for each of the 500 numbers generated with something similar to the following:
$ ./bin/freqarray < <(for i in $(seq 1 500); do
printf " %d" $(($RANDOM %100)); done; echo "done")
Enter any number of integers between 0 and 99 followed a non-numeric:
0 : 4 times
1 : 7 times
2 : 7 times
3 : 4 times
4 : 5 times
5 : 11 times
6 : 5 times
7 : 5 times
8 : 3 times
9 : 8 times
10 : 5 times
...
90 : 8 times
91 : 2 times
92 : 5 times
93 : 8 times
94 : 4 times
95 : 4 times
96 : 8 times
97 : 6 times
98 : 4 times
99 : 8 times
Handling floating-point values
Now if you truly wanted your user to enter floating-point values, e.g. 58.01831, 58.01826538, etc..., conceptually accounting for the frequency of each number isn't any difference, but the implementation is much more involved given the way floating-point numbers are stored in memory. See IEEE floating point and the numerous post on this site. The problems related to floating point storage and exact comparison of random user input can become fairly involved -- quickly. Even for the range of 0-99 there are literally 4e+18+ 64-bit values involved.
As noted in the second comment, one approach that can help is to hash the input values and store the hashed values in a hash-table to reduce the size of the array needed to track/store all values. You will have to balance precision you keep against storage size.
There is no way you could declare an array of 4e+18 elements. A hash table essentially provides a storage and lookup mechanism that can give you reasonable accuracy, and also provides a reasonable storage size. If the user enters 2-values that have the same hash a collision will be generated in your table, which you could use to indicate a duplicate entry. If that was your intent, then you will need to investigate the floating point hash functions available to meet your needs (which from your question, doesn't seem like what you intended, and it well beyond full-explanation here)
Look things over and let me know if you have any questions. If your intent was different, then please edit the question and I'm happy to work with you further.
footnote 1: choose an array type capable of holding the maximum number of entries you expect, e.g. each int element of the array can capture a maximum of INT_MAX, or 2147483647 repetitions (where an int is 32-bits)
footnote 2: C generally favors variable names of all lower-case, and avoids the use of camelCase or MixedCase variable names; reserving all upper-case for constants and macros. It is a matter of style -- so it is completely up to you.
I am trying to write C code which will print the first 1million Fibonacci numbers.
UPDATE: The actual problem is I want to get the last 10 digits of F(1,000,000)
I understand how the sequence works and how to write the code to achieve that however as F(1,000,000) is very large I am struggling to find a way to represent it.
This is code I am using:
#include<stdio.h>
int main()
{
unsigned long long n, first = 0, second = 1, next, c;
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("First %d terms of Fibonacci series are :-\n",n);
for ( c = 0 ; c < n ; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}
return 0;
}
I am using long long to try and make sure there are enough bits to store the number.
This is the output for the first 100 numbers:
First 100 terms of Fibonacci series are :-
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040
1346269
2178309
3524578
5702887
9227465
14930352
24157817
39088169
63245986
102334155
165580141
267914296
433494437
701408733
1134903170
1836311903
-1323752223
512559680
-811192543
-298632863
-1109825406
-1408458269
...
Truncated the output but you can see the problem, I believe the size of the number generated is causing the value to overflow to negative. I don't understand how to stop it in all honesty.
Can anybody point me in the right direction to how to actually handle numbers of this size?
I haven't tried to print the first million because if it fails on printing F(100) there isn't much hope of it printing F(1,000,000).
You want the last 10 digits of Fib(1000000). Read much more about Fibonacci numbers (and read twice).
Without thinking much, you could use some bignum library like GMPlib. You would loop to compute Fib(1000000) using a few mpz_t bigint variables (you certainly don't need an array of a million mpz_t, but less mpz_t variables than you have fingers in your hand). Of course, you won't print all the fibonacci numbers, only the last 1000000th one (so a cheap laptop today has enough memory, and would spit that number in less than an hour). As John Coleman answered it has about 200K digits (i.e. 2500 lines of 80 digits each).
(BTW, when thinking of a program producing some big output, you'll better guess-estimate the typical size of that output and the typical time to get it; if it does not fit in your desktop room -or your desktop computer-, you have a problem, perhaps an economical one: you need to buy more computing resources)
Notice that efficient bignum arithmetic is a hard subject. Clever algorithms exist for bignum arithmetic which are much more efficient than the naive one you would imagine.
Actually, you don't need any bigints. Read some math textbook about modular arithmetic. The modulus of a sum (or a product) is congruent to the sum (resp. the product) of the modulus. Use that property. A 10 digits integer fits in a 64 bits int64_t so with some thinking you don't need any bignum library.
(I guess that with slightly more thinking, you don't need any computer or any C program to compute that. A cheap calculator, a pencil and a paper should be enough, and probably the calculator is not needed at all.)
The lesson to learn when programming (or when solving math exercises) is to think about the problem and try to reformulate the question before starting coding. J.Pitrat (an Artificial Intelligence pioneer in France, now retired, but still working on his computer) has several interesting blog entries related to that: Is it possible to define a problem?, When Donald and Gerald meet Robert, etc.
Understanding and thinking about the problem (and sub-problems too!) is an interesting part of software development. If you work on software developement, you'll be first asked to solve real-world problems (e.g. make a selling website, or an autonomous vacuum cleaner) and you'll need to think to transform that problem into something which is codable on a computer. Be patient, you'll need ten years to learn programming.
To "get the last 10 digits of F(1,000,000)", simply apply the remainder function % when calculating next and use the correct format specifier: "%llu".
There is no need to sum digits more significant than the 10 least significant digits.
// scanf("%d",&n);
scanf("%llu",&n);
...
{
// next = first + second;
next = (first + second) % 10000000000;
first = second;
second = next;
}
// printf("%d\n",next);
printf("%010llu\n",next);
My output (x'ed the last 5 digits to not give-away the final answer)
66843xxxxx
By Binet's Formula the nth Fibonacci Number is approximately the golden ratio (roughly 1.618) raised to the power n and then divided by the square root of 5. A simple use of logarithms shows that the millionth Fibonacci number thus has over 200,000 digits. The average length of one of the first million Fibonacci numbers is thus over 100,000 = 10^5. You are thus trying to print 10^11 = 100 billion digits. I think that you will need more than a big int library to do that.
On the other hand -- if you want to simply compute the millionth number, you can do so -- though it would be better to use a method which doesn't compute all of the intermediate numbers (as simply computing rather than printing them all would still be infeasible for large enough n). It is well known (see this) that the nth Fibonacci number is one of the 4 entries of the nth power of the matrix [[1,1],[1,0]]. If you use exponentiation by squaring (which works for matrix powers as well since matrix multiplication is associative) together with a good big int library -- it becomes perfectly feasible to compute the millionth Fibonacci number.
[On Further Edit]: Here is a Python program to compute very large Fibonacci numbers, modified to now accept an optional modulus. Under the hood it is using a good C bignum library.
def mmult(A,B,m = False):
#assumes A,B are 2x2 matrices
#m is an optional modulus
a = A[0][0]*B[0][0] + A[0][1]*B[1][0]
b = A[0][0]*B[0][1] + A[0][1]*B[1][1]
c = A[1][0]*B[0][0] + A[1][1]*B[1][0]
d = A[1][0]*B[0][1] + A[1][1]*B[1][1]
if m:
return [[a%m,b%m],[c%m,d%m]]
else:
return [[a,b],[c,d]]
def mpow(A,n,m = False):
#assumes A is 2x2
if n == 0:
return [[1,0],[0,1]]
elif n == 1: return [row[:] for row in A] #copy A
else:
d,r = divmod(n,2)
B = mpow(A,d,m)
B = mmult(B,B,m)
if r > 0:
B = mmult(B,A,m)
return B
def Fib(n,m = False):
Q = [[1,1],[1,0]]
return mpow(Q,n,m)[0][1]
n = Fib(999999)
print(len(str(n)))
print(n % 10**10)
googol = 10**100
print(Fib(googol, googol))
Output (with added whitespace):
208988
6684390626
3239047153240982923932796604356740872797698500591032259930505954326207529447856359183788299560546875
Note that what you call the millionth Fibonacci number, I call the 999,999th -- since it is more standard to start with 1 as the first Fibonacci number (and call 0 the 0th if you want to count it as a Fibonacci number). The first output number confirms that there are over 200,000 digits in the number and the second gives the last 10 digits (which is no longer a mystery). The final number is the last 100 digits of the googolth Fibonacci number -- computed in a small fraction of a second. I haven't been able to do a googolplex yet :)
This question comes without doubt from some programming competition, and you have to read these questions carefully.
The 1 millionth Fibonacci number is HUGE. Probably about 200,000 digits or so. Printing the first 1,000,000 Fibonacci number will kill a whole forest of trees. But read carefully: Nobody asks you for the 1 millionth Fibonacci number. You are asked for the last ten digits of that number.
So if you have the last 10 digits of Fib(n-2) and of Fib(n-1), how can you find the last 10 digits of Fib(n)? How do you calculate the last ten digits of a Fibonacci number without calculating the number itself?
PS. You can't print long long numbers with %d. Use %lld.
Your algorithm is actually correct. Since you're using unsigned long long, you have enough digits to capture the last 10 digits and the nature of unsigned overflow functions as modulo arithmetic, so you'll get the correct results for at least the last 10 digits.
The problem is in the format specifier you're using for the output:
printf("%d\n",next);
The %d format specifier expects an int, but you're passing an unsigned long long. Using the wrong format specifier invokes undefined behavior.
What's most likely happening in this particular case is that printf is picking up the low-order 4 bytes of next (as your system seems to be little endian) and interpreting them as a signed int. This ends up displaying the correct values for roughly the first 60 numbers or so, but incorrect ones after that.
Use the correct format specifier, and you'll get the correct results:
printf("%llu\n",next);
You also need to do the same when reading / printing n:
scanf("%llu",&n);
printf("First %llu terms of Fibonacci series are :-\n",n);
Here's the output of numbers 45-60:
701408733
1134903170
1836311903
2971215073
4807526976
7778742049
12586269025
20365011074
32951280099
53316291173
86267571272
139583862445
225851433717
365435296162
591286729879
956722026041
You can print Fibonacci(1,000,000) in C, it takes about 50 lines, a minute and no library :
Some headers are required :
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE (16 * 3 * 263)
#define BUFFERED_BASE (1LL << 55)
struct buffer {
size_t index;
long long int data[BUFFER_SIZE];
};
Some functions too :
void init_buffer(struct buffer * buffer, long long int n){
buffer->index = BUFFER_SIZE ;
for(;n; buffer->data[--buffer->index] = n % BUFFERED_BASE, n /= BUFFERED_BASE);
}
void fly_add_buffer(struct buffer *buffer, const struct buffer *client) {
long long int a = 0;
size_t i = (BUFFER_SIZE - 1);
for (; i >= client->index; --i)
(a = (buffer->data[i] = (buffer->data[i] + client->data[i] + a)) > (BUFFERED_BASE - 1)) && (buffer->data[i] -= BUFFERED_BASE);
for (; a; buffer->data[i] = (buffer->data[i] + a), (a = buffer->data[i] > (BUFFERED_BASE - 1)) ? buffer->data[i] -= BUFFERED_BASE : 0, --i);
if (++i < buffer->index) buffer->index = i;
}
A base converter is used to format the output in base 10 :
#include "string.h"
// you must free the returned string after usage
static char *to_string_buffer(const struct buffer * buffer, const int base_out) {
static const char *alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
size_t a, b, c = 1, d;
char *s = malloc(c + 1);
strcpy(s, "0");
for (size_t i = buffer->index; i < BUFFER_SIZE; ++i) {
for (a = buffer->data[i], b = c; b;) {
d = ((char *) memchr(alphabet, s[--b], base_out) - alphabet) * BUFFERED_BASE + a;
s[b] = alphabet[d % base_out];
a = d / base_out;
}
while (a) {
s = realloc(s, ++c + 1);
memmove(s + 1, s, c);
*s = alphabet[a % base_out];
a /= base_out;
}
}
return s;
}
Example usage :
#include <sys/time.h>
double microtime() {
struct timeval time;
gettimeofday(&time, 0);
return (double) time.tv_sec + (double) time.tv_usec / 1e6;
}
int main(void){
double a = microtime();
// memory for the 3 numbers is allocated on the stack.
struct buffer number_1 = {0}, number_2 = {0}, number_3 = {0};
init_buffer(&number_1, 0);
init_buffer(&number_2, 1);
for (int i = 0; i < 1000000; ++i) {
number_3 = number_1;
fly_add_buffer(&number_1, &number_2);
number_2 = number_3;
}
char * str = to_string_buffer(&number_1, 10); // output in base 10
puts(str);
free(str);
printf("took %gs\n", microtime() - a);
}
Example output :
The 1000000th Fibonacci number is :
19532821287077577316320149475 ... 03368468430171989341156899652
took 30s including 15s of base 2^55 to base 10 conversion.
Also it's using a nice but slow base converter.
Thank You.
I am currently a beginner in programming learning, my professor has instructed me to do a program with the instructions below. However when i wrote my program I did the following to take the input from the user on how long the array should be however because my array size isnt defined it gives me an error but the professor hasnt instructed me to specify a size so im really confused :S
My attempt :
void displayarray(int n){
int i;
int aray[]={0,1};
for (i=0;i<n;i++){
printf("%i", aray[i]);
}
printf("\n");
}
int main()
{ int n;
scanf("%i",&n);
displayarray(n);
getchar();
getchar();
}
The Task assigned:
The Fibonacci numbers are a famous sequence of numbers. They begin with 0 and 1, and then the next value in the sequence is the sum of the previous two values.
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
(fib[8] is 21 -- remember to start counting from 0!)
Write a program that calculates the Fibonacci sequence.
-Make a function that accepts n, which is the number of integers to generate.
-Declare an array, initialize it with only the first two Fibonacci numbers, then calculate the rest.
-Display the sequence for n=10 and n=20.
-Try generating output for n=50. If anything goes wrong in this step, you don't need to fix it. Just add a comment explaining what happens, and why.
You can calculate all the Fibonacci sequence by only using a 3 lenght array. Initialize the first two elements of the array with the two first numbers of the Fibonacci sequence (0 and 1) and then, with these two values, calculate the third number of the sequence.
int f[3];
f[0] = 0;
f[1] = 1;
f[2] = f[0] + f[1]
Try to figure out what to do in the for loop to calculate the Fibonacci number for any integer n.
You can use "malloc()" or "calloc()" function to allocate array of given size.
You need to declare it like
int *array;
array = malloc(n, sizeof(int));
// do something
free(array)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm new to C. I have a class assignment to display a number in a vertical format. If the user enters 5678, the instructor want it to display vertically to the screen in a single column as:
8
7
6
5
Second part of assignment is to find the largest divisor of the same number.
I'm totally lost. I'm getting the NUM value from another function. formula seems to work on even numbers, but on odd.
int divisor (int NUM)
{
int index, count=0;
for(index=2;index<=(NUM/2);index=index+1)
{
if(NUM%index==0)
count++;
}
printf("\n\nThe largest divisor of %d is %d\n",NUM, index-1);
return(index);
}
To display the number vertically:
1. get least significant digit,
2. print it and print new line,
3. shift number to the right by one digit
4. goto 1
Algorithm terminates when the number is zero. Call the input number n; getting the least significant (rightmost) digit can be done with n % 10. Right shift can be done with n = n / 10.
For the second part, observe that the largest divisor cannot be more than n/2 (because n = 2 * n/2). So try all number from n/2 down to 1 and break once you find a divisor. You will find the largest divisor because you are considering numbers in decreasing order. To check that x divides y use y % x == 0.
A second way it to check numbers from sqrt(n) down to 1. If m divides n, we can write n = m * k for some k. Now you take max(m, n/m) and continue.
Hope this helps :)
For the first part, there are many ways to approach this. But, without using too many of the standard library functions which seems to be a level appropriate for the question, I think the easiest way would be to take the numbers as a character array. Then access each value through it's index in the character array. This requires only the stdio.h header file. Some quick notes: simply use printf to print the value contained at each index, and throw the newline \n character at the end. If you wanted convert the string to an integer, you can do that very easily using the function atoi() which can be found in stdlib.h. If you want to print out backward, you can simply traverse the array backward.
void displayvert(char str[])
{
int i;
for (i = 0; str[i] != '\0'; ++i) {
printf("%c\n", str[i]);
}
}
Also many ways to approach the second, but in this case for the second question I think I'd use the modulus operator and track the highest value where the result is zero. In order for this to work with the single user provided input, I actually needed atoi() which is in the stdlib.h header. Basically, starting from the value one you'll increase the value up the integer just below the value of 'num' itself. And, if the remainder is zero when you when you divide by it (the purpose of using the modulus operator) then you know it's divisible. Because we're ascending from 1 to the number itself, the last value to return a remainder of zero is the greatest common divisor.
void getgcd(int num)
{
int i, gcd;
// remember, you can't do x % 0!
for (i = 1; i < num; i++) {
if ((num % i) == 0 ) {
gcd = i;
}
}
printf("The greatest common divisor is: %d\n", gcd);
}
Main function and prototypes here so you can see how it all tied together. A couple of quick notes (1) 11 digits was arbitrary; but it's important to note that we used 10 digits for the total input value (you can add checks to this to enforce) and reserved the 11th (at index 10) to allow space for the null terminating character \0. (2) Use scanf to grab input; note that because character arrays do not require the address operator & because it defaults to that.
#include <stdio.h>
#include <stdlib.h>
void displayvert(char str[]);
void getgcd(int num);
int main()
{
char input[11]; // additional character added for \0
printf("Please enter a value up to 10 digits: ");
scanf("%s", input);
displayvert(input);
getgcd(atoi(input));
return 0;
}
Write a program that sums the sequence
of integers as well as the smallest in
the sequence. Assume that the first
integer read with scanf specifies the
number of values remaining to be
entered. For example the sequence
entered:
Input: 5 100 350 400 550 678
Output: The sum of the sequence of
integers is: 2078
Input: 5 40 67 9 13 98
Output: The smallest of the integers
entered is: 9
This is a daily problem I am working on but by looking at this, Isnt 5 the smallest integer? I have no idea how to write this program. Appreciate any help
First thing, the 5 is not considered part of the list, it's the count for the list. Hence it shouldn't be included in the calculations.
Since this is homework, here's the pseudo-code. Your job is to understand the pseudo-code first (run it through your head with sample inputs) then turn this into C code and try to get it compiling and running successfully (with those same sample inputs).
I would suggest the sample input of "2 7 3" (two items, those being 7 and 3) as a good start point since it's small and the sum will be 10, smallest 3.
If you've tried to do that for more than a day, then post your code into this question as an edit and we'll see what we can do to help you out.
get a number into quantity
set sum to zero
loop varying index from 1 to quantity
get a number into value
add value to sum
if index is 1
set smallest to value
else
if value is less than smallest
set smallest to value
endif
endif
endloop
output "The sum of the sequence of integers is: ", sum
output "The smallest of the integers entered is: ", smallest
Stack Overflow seems to be divided into three camps, those that will just give you the code, those that will tell you to push off and do your own homework and those, like me, who would rather see you educated - by the time you hit the workforce, I hope to be retired so you won't be competing with me :-).
And before anyone picks holes in my algorithm, this is for education. I've left at least one gotcha in it to help train the guy - there may be others and I will claim I put them there intentionally to test him :-).
Update:
Robert, after your (very good) attempt which I've already commented on, this is how I'd modify your code to do the task (hand yours in of course, not mine). You can hopefully see how my comments modify the code to reach this solution:
#include <stdio.h>
int main (int argCount, char *argVal[]) {
int i; // General purpose counter.
int smallNum; // Holds the smallest number.
int numSum; // Holds the sum of all numbers.
int currentNum; // Holds the current number.
int numCount; // Holds the count of numbers.
// Get count of numbers and make sure it's in range 1 through 50.
printf ("How many numbers will be entered (max 50)? ");
scanf ("%d", &numCount);
if ((numCount < 1) || (numCount > 50)) {
printf ("Invalid count of %d.\n", numCount);
return 1;
}
printf("\nEnter %d numbers then press enter after each entry:\n",
numCount);
// Set initial sum to zero, numbers will be added to this.
numSum = 0;
// Loop, getting and processing all numbers.
for (i = 0; i < numCount; i++) {
// Get the number.
printf("%2d> ", i+1);
scanf("%d", ¤tNum);
// Add the number to sum.
numSum += currentNum;
// First number entered is always lowest.
if (i == 0) {
smallNum = currentNum;
} else {
// Replace if current is smaller.
if (currentNum < smallNum) {
smallNum = currentNum;
}
}
}
// Output results.
printf ("The sum of the numbers is: %d\n", numSum);
printf ("The smallest number is: %d\n", smallNum);
return 0;
}
And here is the output from your sample data:
pax> ./qq
How many numbers will be entered (max 50)? 5
Enter 5 numbers then press enter after each entry:
1> 100
2> 350
3> 400
4> 550
5> 678
The sum of the numbers is: 2078
The smallest number is: 100
pax> ./qq
How many numbers will be entered (max 50)? 5
Enter 5 numbers then press enter after each entry:
1> 40
2> 67
3> 9
4> 13
5> 98
The sum of the numbers is: 227
The smallest number is: 9
pax> ./qq
How many numbers will be entered (max 50)? 0
Invalid count of 0.
[fury]$ ./qq
How many numbers will be entered (max 50)? 51
Invalid count of 51.
By the way, make sure you always add comments to your code. Educators love that sort of stuff. So do developers that have to try to understand your code 10 years into the future.
Read:
Assume that the first integer read
with scanf specifies the number of
values remaining to be entered
so it's not part of the sequence...
for the rest, it's your homework (and C...)
No. 5 is the number of integers you have to read into the list.
Jeebus, I'm not doing your homework for you, but...
Have you stopped to scratch this out on paper and work out how it should work? Write some pseudo-code and then transcribe to real code. I'd have thought:
Read integer
Loop that many times
** Read more integers
** Add
** Find Smallest
IF you're in C look at INT_MAX - that will help out finding the smallest integer.
Since the list of integers is variable, I'd be tempted to use strtok to split the string up into individual strings (separate by space) and then atoi to convert each number and sum or find minimum on the fly.
-Adam
First you read the number of values (ie. 5), then create an array of int of 5 elements, read the rest of the input, split them and put them in the array (after converting them to integers).
Then do a loop on the array to get the sum of to find the smallest value.
Hope that helps
wasn[']t looking for you guys to do the work
Cool. People tend to take offense when you dump the problem text at them and the problem text is phrased in an imperative form ("do this! write that! etc.").
You may want to say something like "I'm stuck with a homework problem. Here's the problem: write a [...]. I don't understand why [...]."
#include <stdio.h>
main ()
{
int num1, num2, num3, num4, num5, num6, i;
int smallestnumber=0;
int sum=0;
int numbers[50];
int count;
num1 = 0;
num2 = 0;
num3 = 0;
num4 = 0;
num5 = 0;
num6 = 0;
printf("How many numbers will be entered (max 50)? ");
scanf("%d", &count);
printf("\nEnter %d numbers then press enter after each entry: \n", count);
for (i=0; i < count; i++) {
printf("%2d> ", i+1);
scanf("%d", &numbers[i]);
sum += numbers[i];
}
smallestnumber = numbers[0];
for (i=0; i < count; i++) {
if ( numbers[i] < smallestnumber)
{
smallestnumber = numbers[i];
}
}
printf("the sum of the numbers is: %d\n", sum);
printf("The smallest number is: %d", smallestnumber);
}