printf executes multiple times only on certain inputs - printf

Program executes the printf command multiple times when the input is "08" or "09" and not in some other similar number, say "03" or "07".
do
{
printf("Enter date:");
scanf("%i/%i/%i", &d, &m, &y);
}
while (d !=0 || m != 0 || y != 0);
This is the output (numbers are entered by user) -
Enter date:3/6/8
Enter date:3/6/08
Enter date:Enter date:04/05/06
Enter date:08/08/08
Enter date:Enter date:Enter date:Enter date:01/02/03
Enter date:04/05/06
Why is this happening and how can I fix it ?

Hasn't been answered yet so this wouldn't hurt.
I'm not sure if it's right but as I read more about C today, my guess is it must be happening because scanf is reading the input as an octal number because it starts from zero. And the strange behaviour might be because there is no 08 and 09 in octal.

Related

What is Pseudo-polynomial complexity?

Yes, I've seen this answer - What is pseudopolynomial time? How does it differ from polynomial time? - but I still don't understand.
Why does the representation in bits make a difference only sometimes?
For this program for example
function isPrime(n):
for i from 2 to n - 1:
if (n mod i) = 0, return false
return true
it says the complexity is not polynomial, because n requires log n bits to write out so the complexity is O(2^(4*log n)) but if i use that on every other problem then it could also be pseudopolynomial, right? (unless im getting it all wrong here). What makes this program so special to be measured in the amount of bits required to write out n?
You have linked to other questions where this is explained fairly well for someone who understands the concept, so here comes a very brief version.
for i from 2 to n - 1:
can be rewritten as
i = 2
while(i < n - 1):
if (n mod i) == 0:
return false
i = i + 1
Very often, we assume that the operations i < n - 1, i = i + 1 and n mod i are O(1). But this is not necessarily true. It is usually true for small values. And on a 32 bit machine, a "small value" is in the order of a billion.
Number that requires more than 32 bits to be represented will take more time to perform operations on than a number that fits in 32 bit. And it will take even more if it required more than 64 bit.
In practice, this rarely matters.
A very simple way to visualize this is to imagine that you get the task to implement the common mathematical operations where the operands are represented as strings. Here is a simple python function that takes two strings representing binary numbers and returns the sum as a string. It was quickly hacked together and assumes both strings has the same length. It may contain bugs and can most likely be refined. But it demonstrate the point. This function adds two numbers, but it will take longer time for longer numbers.
def binadd(a, b):
carry = '0'
result = list('0'*(len(a)+1))
for i in range(len(a)-1,-1, -1):
xor = '1' if (a[i] == '1') != (b[i] == '1') else '0'
val = '1' if (xor == '1') != (carry == '1') else '0'
carry = '1' if (carry == '1' and xor == '1') or (a[i] == '1' and b[i] == '1') else '0'
result[i] = val
result[0]=carry
return ''.join(result)
What makes this program so special to be measured in the amount of bits required to write out n?
There's nothing special about this particular program. At least not theoretical. In practice it is special in the sense that determining if a VERY big number is a prime is a common problem. Or to be more accurate, it would have been a much more common problem if there existed a very fast algorithm to do it. If it did, it would basically break encryption as we know it today.

16-digit number manipulation on a 32-bit programming language

I have a simple problem, but because this "programming language" I am using is 32-bit and only supports basic functions such as addition, subtraction, multiplication, division, and concatenation (literally that's it), I am having some trouble.
For the input, I have a 16 digit number like so: 3334,5678,9523,4567
I want to then subtract 2 other random 16 digit numbers from this number and check if the first and last digits are 1.
For example, if the two other numbers are 1111,1111,1111,1111 and 1234,5678,9123,4565.
My final number would be: 0988,8888,9288,8891.
Here, the last number is 1, but the first number is 0, so the test would fail.
The issue is with 32-bit systems, there are massive errors due to not enough precision provided by the bits. What are some ways to bypass this issue?
If you're using a language like C or Java you should be able to use a long to create a 64 bit integer. If that's not possible you could divide the numbers into two 32 bit numbers, one to hold the upper half and one to hold the lower half.
Something like this:
//Each half is 8 digits to represent 8 of the 16
//Because of this each half should be less than 100000000
int upperHalf = 33345678;
int lowerHalf = 95234567;
//randomInt represents a function to generate a random
//integer equal to or greater than 0 and less than the
//argument passed to it
int randUpperHalf = randomInt(100000000);
int randLowerHalf = randomInt(100000000);
int lowerHalf = lowerHalf - randLowerHalf;
//If lowerHalf was a negative number you need to borrow from the upperHalf
if (lowerHalf < 0) {
upperHalf = upperHalf - 1;
lowerHalf = lowerHalf + 100000000;
}
upperHalf = upperHalf - randUpperHalf;
//Check that the first and last digits are 1
if ((upperHalf / 100000000) == 1 && (lowerHalf % 10) == 1) {
//The first and last digits are 1
}
Edit: Comments have been added to explain the code better. (lowerHalf % 2) == 1 has been changed to (lowerHalf % 10) == 1 and should now be able to tell if the number ends in a 1.

'while' Loop in Objective-C

The following program calculates and removes the remainder of a number, adds the total of the remainders calculated and displays them.
#import <Foundation/Foundation.h>
int main (int argc, char * argv[]) {
#autoreleasepool {
int number, remainder, total;
NSLog(#"Enter your number");
scanf("%i", &number);
while (number != 0)
{
remainder = number % 10;
total += remainder;
number /= 10;
}
NSLog(#"%i", total);
}
return 0;
}
My questions are:
Why is the program set to continue as long as the number is not equal to 0? Shouldn't it continue as the long as the remainder is not equal to 0?
At what point is the remainder discarded from the value of number? Why is there no number -= remainder statement before n /=10?
[Bonus question: Does Objective-C get any easier to understand?]
The reason we continue until number != 0 instead of using remainder is that if our input is divisible by 10 exactly, then we don't get the proper output (the sum of the base 10 digits).
The remainder is dropped off because of integer division. Remember, an integer cannot hold a decimal place, so when we divide 16 by 10, we don't get 1.6, we just get 1.
And yes, Objective-C does get easier over time (but, as a side-note, this uses absolutely 0 features of Objective-C, so it's basically C with a NSLog call).
Note that the output isn't quite what you would expect at all times, however, as in C / ObjC, a (unlike languages like D or JS) a variable is not always initialized to a set value (in this case, you assume 0). This could cause UB down the road.
It checks to see if number is not equal to zero because remainder very well may never become zero. If we were to input 5 as our input value, the first time through the loop remainder would be set to 5 (because 5 % 10 = 5), and number would go to zero because
5 / 10 = 0.5, and ints do not store floating point values, so the .5 will get truncated and the value of number will equal zero.
The remainder does not get removed from the value of number in this code. I think that you may be confused about what the modulo operator does (see this explanation).
Bonus answer: learning a programming language is difficult at first, but very rewarding in the long run (if you stick with it). Each new language that you learn after your first will most likely be easier to learn too, because you will understand general programming constructs and practices. The best of luck on your endeavor!

Looping until multiple conditions reached in Objective-C

So i am trying to create a program that can find a number that can be divided by numbers 1-20. I know that i will have to use the following simple code concepts:
I know how loops work and how to create a loop that runs until a condition is met. Is there a simple was to run a loop until several conditions are met?
while ( condition1 && condition2 && condition3... ) {}
or
for ( int i = 0; i < n && condition1 && condition2... ) {}
Obviously these will loop while the conditions are true, not until the conditions are met. Its a simple change in the logic though to get the result you want
EDIT
Ane example of the kind of loop youre looking for could be like:
int number = ...;//initialized somewhere, this is what we're checking
BOOL divisible = YES;
for ( int i = 1; i <= 20 && divisible; ++i )
{
if ( (number % i) != 0 )
divisible = NO;//not divisible by i
}
Good answers in play, but I think it's good to mention the break operator in this discussion. Any loop, at any time, can be terminated using this operator. This can be helpful if you do not know all of the parameters which might go out-of-bounds, and you want to have a way of breaking the loop for reasons you may not have explicitly anticipated (i.e. perhaps your connection to a resource is no longer available...)
NSError *error = nil;
while(true) {
// run your app
if(error) {
break;
}
}
If a number is divisible by all numbers from 1 to 20 then it is divisible by the LCM of 1 to 20 so divisibility test is if(!(n%232792560)).
Further if m = pq | n then p|n, q|n so to explicitly test you only need to check for divisibility by primes. i.e if the number is not even then there is no need to check for divisibility by 4, 6, 8, 10, 12, 14, 16, 18 or 20. This reduces the test to the number being congruent to the 8th primorial = 9699690
OK, perhaps on second reading not as explicit as I should like: the expanded test looks like (by de Morgan's theorem)
if(!(n%19 || n%17 || n%16 || n%13 || n%11 || n%9 || n%7 || n%5))
// number is divisible by 1..20

Reading a known number of variable from a file when one of the variables are missing in input file

I already checked similar posting. The solution is given by M. S. B. here Reading data file in Fortran with known number of lines but unknown number of entries in each line
So, the problem I am having is that from text file I am trying to read inputs. In one line there is supposed to be 3 variables. But sometimes the input file may have 2 variables. In that case I need to make the last variable zero. I tried using READ statement with IOSTAT but if there is only two values it goes to the next line and reads the next available value. I need to make it stop in the 1st line after reading 2 values when there is no 3rd value.
I found one way to do that is to have a comment/other than the type I am trying to read (in this case I am reading float while a comment is a char) which makes a IOSTAT>0 and I can use that as a check. But if in some cases I may not have that comment. I want to make sure it works even than.
Part of the code
read(15,*) x
read(15,*,IOSTAT=ioerr) y,z,w
if (ioerr.gt.0) then
write(*,*)'No value was found'
w=0.0;
goto 409
elseif (ioerr.eq.0) then
write(*,*)'Value found', w
endif
409 read(15,*) a,b
read(15,*) c,d
INPUT FILE is of the form
-1.000 abcd
12.460 28.000 8.00 efg
5.000 5.000 hijk
20.000 21.000 lmno
I need to make it work even when there is no "8.00 efg"
for this case
-1.000 abcd
12.460 28.000
5.000 5.000 hijk
20.000 21.000 lmno
I can not use the string method suggested by MSB. Is there any other way?
I seem to remember trying to do something similar in the past. If you know that the size of a line of the file won't exceed a certain number, you might be able to try something like:
...
character*(128) A
read(15,'(A128)') A !This now holds 1 line of text, padded on the right with spaces
read(A,*,IOSTAT=ioerror) x,y,z
if(IOSTAT.gt.0)then
!handle error here
endif
I'm not completely sure how portable this solution is from one compiler to the next and I don't have time right now to read up on it in the f77 standard...
I have a routine that counts the number of reals on a line. You could adapt this to your purpose fairly easily I think.
subroutine line_num_columns(iu,N,count)
implicit none
integer(4),intent(in)::iu,N
character(len=N)::line
real(8),allocatable::r(:)
integer(4)::r_size,count,i,j
count=0 !Set to zero in case of premature return
r_size=N/5 !Initially try out this max number of reals
allocate(r(r_size))
read(iu,'(a)') line
50 continue
do i=1,r_size
read(line,*,end=99) (r(j),j=1,i) !Try reading i reals
count=i
!write(*,*) count
enddo
r_size=r_size*2 !Need more reals
deallocate(r)
allocate(r(r_size))
goto 50
return
99 continue
write(*,*) 'I conclude that there are ',count,' reals on the first line'
end subroutine line_num_columns
If a Fortran 90 solution is fine, you can use the following procedure to parse a line with multiple real values:
subroutine readnext_r1(string, pos, value)
implicit none
character(len=*), intent(in) :: string
integer, intent(inout) :: pos
real, intent(out) :: value
integer :: i1, i2
i2 = len_trim(string)
! initial values:
if (pos > i2) then
pos = 0
value = 0.0
return
end if
! skip blanks:
i1 = pos
do
if (string(i1:i1) /= ' ') exit
i1 = i1 + 1
end do
! read real value and set pos:
read(string(i1:i2), *) value
pos = scan(string(i1:i2), ' ')
if (pos == 0) then
pos = i2 + 1
else
pos = pos + i1 - 1
end if
end subroutine readnext_r1
The subroutine reads the next real number from a string 'string' starting at character number 'pos' and returns the value in 'value'. If the end of the string has been reached, 'pos' is set to zero (and a value of 0.0 is returned), otherwise 'pos' is incremented to the character position behind the real number that was read.
So, for your case you would first read the line to a character string:
character(len=1024) :: line
...
read(15,'(A)') line
...
and then parse this string
real :: y, z, w
integer :: pos
...
pos = 1
call readnext_r1(line, pos, y)
call readnext_r1(line, pos, z)
call readnext_r1(line, pos, w)
if (pos == 0) w = 0.0
where the final 'if' is not even necessary (but this way it is more transparent imho).
Note, that this technique will fail if there is a third entry on the line that is not a real number.
I know the following simple solution:
w = 0.0
read(15,*,err=600)y, z, w
goto 610
600 read(15,*)y, z
610 do other stuff
But it contains "goto" operators
You might be able to use the wonderfully named colon edit descriptor. This allows you to skip the rest of a format if there are no further items in the I/O list:
Program test
Implicit None
Real :: a, b, c
Character( Len = 10 ) :: comment
Do
c = 0.0
comment = 'No comment'
Read( *, '( 2( f7.3, 1x ), :, f7.3, a )' ) a, b, c, comment
Write( *, * ) 'I read ', a, b, c, comment
End Do
End Program test
For instance with gfortran I get:
Wot now? gfortran -W -Wall -pedantic -std=f95 col.f90
Wot now? ./a.out
12.460 28.000 8.00 efg
I read 12.460000 28.000000 8.0000000 efg
12.460 28.000
I read 12.460000 28.000000 0.00000000E+00
^C
This works with gfortran, g95, the NAG compiler, Intel's compiler and the Sun/Oracle compiler. However I should say I'm not totally convinced I understand this - if c or comment are NOT read are they guaranteed to be 0 and all spaces respectively? Not sure, need to ask elsewhere.