Try unpairing it and re-pairing it (Bluetooth icon in menu bar), turn off the mac, turn on the keyboard, turn on the iMac and it should detect that no keyboard is attached, and re-pair itself with the detected keyboard.
If this does not fix it, take it to an Apple Store and tell a genius about your problem, they should replace it for you