Prime decomposition - prime-factoring

I'm trying to take a user-entered number and determine if it's a prime number or not. If it is not prime, I want to display the prime factors for that number. I need to use only JOptionPane. No matter what I try my code doesn't read any odd numbers (21, 25, 105 etc) as primes even though they are. What am I doing wrong?
do
{
enteredNum = JOptionPane.showInputDialog(null, "Please enter a positive"
+ " integer","enter number",1);
int number = Integer.parseInt(enteredNum); //Enter number and convert to integer
if (number < 0){
break;
}
counter = 2;
isPrime = true;
while(isPrime && (counter < number)){
if((number%counter)== 0){
isPrime = false;
JOptionPane.showMessageDialog(null, "Your entered number, "+number+" is not prime."
+ "\nIts prime decomposition is "+counter+" X "+(number/counter)+".",
"Prime number", 1);
break;
}
else {
counter = counter + 1;
JOptionPane.showMessageDialog(null, number+"is a prime number", "Prime number", 1);
break;
}
}

Related

CompressedInt Write?

public static function Read(param1:IDataInput) : int
{
var _loc2_:* = 0;
var _loc3_:int = param1.readUnsignedByte();
var _loc4_:* = (_loc3_ & 64) != 0;
var _loc5_:int = 6;
_loc2_ = _loc3_ & 63;
while(_loc3_ & 128)
{
_loc3_ = param1.readUnsignedByte();
_loc2_ = _loc2_ | (_loc3_ & 127) << _loc5_;
_loc5_ = _loc5_ + 7;
}
if(_loc4_)
{
_loc2_ = int(-_loc2_);
}
return _loc2_;
}
someone can help me with write thing?
about to use in as3 server based but got only read thing
As #Organis correctly said "there's no telling how to compose a reverted algorithm."
The only obvious things are listed below, so you'll have to do a lot of testing to get it right (that's how reverse engineering works, and it might take days or weeks). Good luck.
Assessment:
(1)
public static function Read(param1:IDataInput) : int
Look like it expects a (byte) array with two entries. I suspect you should write a Short (in hex formnat) but it'll be easier to just write two separate decimal values (since a Short is a value that spreads over two bytes).
public static function Write(val1 :int, val2 :int, targetBA :ByteArray) : void
{
targetBA.length = 2;
targetBA.position = 0;
targetBA.writeByte( val1 );
targetBA.writeByte( val2 );
//# target ByteArray can now be "Read" by the other function as "param1"
}
As for the Read side...
Since the function returns a value to update some var, you should use as:
myResult = Read( targetBA );
Where myResult gets the function's returned _loc2_ result.
(2)
var _loc4_:* = ( (_loc3_ & 64) != 0 );
This will give either a 0 or 64. Is 0 if lower than 64, or else is 64 if equal or higher.
This is likely a quick shortcut to setting a Boolean like:
var _loc4_ :Boolean;
if (_loc3_ >= 64) { _loc4_ = true}
else { _loc4_ = false; }
(3)
_loc2_ = _loc3_ & 63;
Where _loc2_ is set as an integer of either 0 or 63.
(4)
while(_loc3_ & 128)
I don't know what this is trying to achieve. (_loc3_ & 128) is either 0 or 128.
This While(0) or While(128) loop will run forever and there isn't any stopping break; at the end.
(5)
_loc2_ = _loc2_ | (_loc3_ & 127) << _loc5_;
This updates _loc2_ with two values. The current loc2 value is combined with a modified loc3 value.
(6)
if(_loc4_)
Likely means if( _loc4_ == true )...

Misunderstanding of the OOP in a chess game design in java

I've a problem with code that I'm writing to practice my java skills.
I'm trying to write a chess game. Anyway, in my project I have a class called ChessGUI which contains the GUI and the methods I need to play (multiplayer). I'm willing to change the code later to a MVC pattern so it can be easier to read/edit/understand.
I've an abstract class called Figure and i extended it in 12 classes (6 figures per color):
However in my ChessGui class I have a method called CheckAvailableSquares() which I call whenever a piece on the board has been selected (by a mouse click) to show me on the board the available squares which I can move my selected piece to.
private void CheckAvailableSquares(Figure figure){
for (int row = 0; row < 8; row++){
for (int col = 0; col < 8; col++){
if (row == figure.getRowPos() && col == figure.getColPos()) //bypass the actual square where my piece stands
continue;
if (figure.isValidMove(board,figure.getRowPos(), figure.getColPos(),row,col)){
board[row][col].setBackground(Color.GREEN);
}
}
}
}
In every figure sub-class there is a method called isValidMove() which becomes the current position of the piece and the wanted position and return a boolean value if the move is valid.
As you know the pawn can move 2 squares per time on it's first move, that's why I added a boolean attribute to the classes WhitePawn&BlackPawn called firstMovePlayed. It has the false value and whenever the isMoveValid() method is called and the wanted move is valid it should be changed to true. like that:
public class WhitePawn extends Figure {
private boolean firstMovePlayed = false;
public WhitePawn(){
super.setColor(Color.WHITE);
}
#Override
public boolean isValidMove(Square[][] board, int currentRow, int currentCol, int wantedRow, int wantedCol){
int rowDelta = currentRow - wantedRow; //no Math.abs because a pawn can't move backwards.
int colDelta = Math.abs(wantedCol - currentCol);
//if we have an own piece on the wanted square
if (!board[wantedRow][wantedCol].isEmpty() && board[wantedRow][wantedCol].getFigure().getColor().equals(Color.WHITE)) {
return false;
}
//on the first move a pawn can move 2 square at a time, and when moving 2 square he can't capture. A pawn can't move two square if there is another piece in the way. TODO: en passant ??????
if (rowDelta == 2 && colDelta == 0 && board[wantedRow][wantedCol].isEmpty() && board[wantedRow + 1][wantedCol].isEmpty() && !firstMovePlayed) {
firstMovePlayed = true;
return true;
}
else if (rowDelta == 1 && colDelta == 1 && !board[wantedRow][wantedCol].isEmpty()) { //capture
if (board[wantedRow][wantedCol].getFigure().getColor() != board[currentRow][currentCol].getFigure().getColor())
firstMovePlayed = true;
return true;
}
else if (rowDelta == 1 && colDelta == 0 && board[wantedRow][wantedCol].isEmpty()) { //moving one square forward without a capture
firstMovePlayed = true;
return true;
}
//those were the only possibilities to move a pawn
return false;
}}
The problem is:
whenever I call the method CheckAvailableSquares() to check the availability of the squares the firstMovePlayed boolean will be set to true!!
I'm really sorry for taking too long of your time but I really can't figure it out :/
here is the rest of the relevant code from ChessGui class:
public void actionPerformed(ActionEvent e) {
//looking for the square which fired the ActionListener:
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
if(board[i][j] == e.getSource()){
processClick(i, j);
}
}
}
}
private void processClick(int i, int j){
if(bufRow == 99 && bufCol == 99){ //select a figure to move and wait for the next click
if (board[i][j].isEmpty()) { //if there is no figure on the square that has benn clicked
System.out.println("no Figures on this square");
return;
}
else {//save the chosen square (button) in buffers so that we can move it later.
//decide who's turn it is:
if (board[i][j].getFigure().getColor().equals(Color.WHITE) && !whiteToPlay)
System.out.println("It's black's turn to play!");
else if (board[i][j].getFigure().getColor().equals(Color.BLACK) && !blackToPlay)
System.out.println("It's white's turn to play!");
if ((board[i][j].getFigure().getColor().equals(Color.WHITE) && whiteToPlay) || board[i][j].getFigure().getColor().equals(Color.BLACK) && blackToPlay) {
board[i][j].setHighleightedIcon(board[i][j].getFigure().getHilightedIcon()); //change the icon of the chosen square
bufRow = i; //save the chosen figure to move it later
bufCol = j;
System.out.println("Selectd figure on Raw: " + bufRow + " Column: " + bufCol);
switchTurns();
CheckAvailableSquares(board[bufRow][bufCol].getFigure());
}
}
}
else
moveFigure(i, j);
}
private void moveFigure(int wantedRow, int wantedCol) {
if (board[bufRow][bufCol].getFigure().isValidMove(board, bufRow, bufCol, wantedRow, wantedCol)) { // check if the move is valid for the figure
// if (board[wantedRow][wantedCol].isEmpty()) { //if the wanted square is empty (not a capture)
//move the figure to the wanted square after deleting it from the old square
board[wantedRow][wantedCol].setFigure(board[bufRow][bufCol].getFigure());
board[wantedRow][wantedCol].setSquareIcon(board[bufRow][bufCol].getFigure().getIcon());
board[bufRow][bufCol].emptySquare();
//update the location of the piece
board[wantedRow][wantedCol].getFigure().setNewPos(wantedRow,wantedCol);
System.out.println("Moved [" + bufRow + ", " + bufCol + "] To: [" + wantedRow + ", " + wantedCol + "].");
//reset the buffers
bufRow = 99;
bufCol = 99;
resetSquaresColors();
/*}
else if (!board[wantedRow][wantedCol].isEmpty()){ //if it's a capture
if(board[wantedRow][wantedCol].getFigure().getColor() != board[bufRow][bufCol].getFigure().getColor()) { //can't capture own pieces!
board[wantedRow][wantedCol].setFigure(board[bufRow][bufCol].getFigure());
board[wantedRow][wantedCol].setSquareIcon(board[wantedRow][wantedCol].getFigure().getIcon());
board[bufRow][bufCol].emptySquare();
//update the location of the piece
board[wantedRow][wantedCol].getFigure().setRowPos(wantedRow);
board[wantedRow][wantedCol].getFigure().setColPos(wantedCol);
System.out.println("Moved [" + bufRow + ", " + bufCol + "] To: [" + wantedRow + ", " + wantedCol + "].");
//reset the buffers
bufRow = 99;
bufCol = 99;
}
}*/
} else { //if it's not a valid move
board[bufRow][bufCol].setIcon(board[bufRow][bufCol].getFigure().getIcon());
//reset the buffers
bufRow = 99;
bufCol = 99;
resetSquaresColors();
System.out.println("Not a valid move");
switchTurns();
}
}
private void CheckAvailableSquares(Figure figure){
for (int row = 0; row < 8; row++){
for (int col = 0; col < 8; col++){
if (row == figure.getRowPos() && col == figure.getColPos()) //bypass the actual square where my piece stands
continue;
if (figure.isValidMove(board,figure.getRowPos(), figure.getColPos(),row,col)){
Square sqr = board[row][col];
if (sqr.isEmpty()) //if the square is empty
sqr.setAvailableIcon(new ImageIcon("Icons/available_square.png"));
else //if there is a piece on the square
sqr.setAvailableIcon(sqr.getFigure().getAvailableIcon());
}
}
}
}
Thanks alot & forgive any mistakes in my poor English!

Flex (ActionScript 3): How to find that a string contain a repeating character more than 6 times?

How I find that string contains a repeating character more than 6 times in Flex?
In my case, the user input is only digits (0-9) and I am doing for US Fax no validation.
like 11111112255, 225555555522, etc
A regular expression way:
/(.)\1{6}/
This will search for any character (not necessarily digit) repeated 7 times.
/(\d)\1{6}/
The same, but for digits only.
There are techniques that will be generally faster than regexp, for example, slightly modified Bitap algorithm may prove to be faster.
Here's an altered version of Bitup algorithm to search for repeating characters in a string:
package
{
import flash.display.Sprite;
public class BitapConsequent extends Sprite
{
public function BitapConsequent()
{
super();
test();
}
private function test():void
{
// 10 -1 3 0
trace(bitapConsequent("---####$$$^^^^^^", 6),
bitapConsequent("---####$$$^^^^^^", 7),
bitapConsequent("---####$$$^^^^^^", 4),
bitapConsequent("---####$$$^^^^^^", 3));
}
private static function bitapConsequent(
text:String, consequent:uint):int
{
// Unless found, the result is negative
var result:int = -1;
var len:int = text.length;
var offset:int;
var reverse:int;
if (len >= consequent)
{
consequent--;
len -= consequent;
// loop through the whole string sans
// the substring which is shorter than
// the number of characters that have to
// be the same
outer: for (; offset < len; offset++)
{
// jump to the farmost end of the possible
// match and walk back checking that each
// two characters match, i.e. if this is
// the array of characters a = ['a', 'b', 'b']
// then first check if a[2] == a[1], then
// if a[1] == a[0], if characters are equal,
// continue to the next iteration, else--
// restart the search
for (reverse = offset + consequent;
reverse > offset; reverse--)
{
if (text.charAt(reverse) !==
text.charAt(reverse - 1))
continue outer;
}
// If we got here, we've found `consequent'
// equal characters, so terminate the loop
result = offset;
break;
}
}
return result;
}
}
}
The earlier version indeed used bitup algorithm, but after some thought, I've realized it wasn't required, so this is a bit more refined version, which also doesn't limit one to the 32-characters matches only.
You can use a regex:
var testString:String = "1111111";
if ( testString.search( /[0-9]{7}/ ) != -1 )
trace( "The string '" + testString + "' contains more than 6 repeating digits" );
Edit:
As #wvxvw points out, this will break if your string is something like 1112222 or 1234567 - his regex gets around that
I do this in this way,
<?xml version="1.0" encoding="utf-8"?>
<fx:Script>
<![CDATA[
import mx.controls.Alert;
protected function button1_clickHandler(event:MouseEvent):void
{
if(id_input.text.length >=10)
{
for(var i:uint=0; i<4; i++)
{
var counter:int = 0;
var str:String = id_input.text.substr(i,1);
var index:uint = 0;
index = i;
index += 1;
//case 1
if(str == id_input.text.substr(index ,1))
counter ++;
index += 1;
//case 2
if(str == id_input.text.substr(index ,1))
counter ++;
index += 1;
//case 3
if(str == id_input.text.substr(index ,1))
counter ++;
index += 1;
//case 4
if(str == id_input.text.substr(index ,1))
counter ++;
index += 1;
//case 5
if(str == id_input.text.substr(index ,1))
counter ++;
index += 1;
//case 6
if(str == id_input.text.substr(index ,1))
counter ++;
if(counter >= 6){
Alert.show('More then 6 char present in string');
break;
}
}
}
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:VGroup width="100%" height="100%">
<s:TextInput id="id_input"/>
<s:Button label="Validate" click="button1_clickHandler(event)" />
</s:VGroup>

C++ ROT13 Function Crashes

I'm not too good with C++, however; my code compiled, but the function crashes my program, the below is a short sum-up of the code; it's not complete, however the function and call is there.
void rot13(char *ret, const char *in);
int main()
{
char* str;
MessageBox(NULL, _T("Test 1; Does get here!"), _T("Test 1"), MB_OK);
rot13(str, "uryyb jbeyq!"); // hello world!
/* Do stuff with char* str; */
MessageBox(NULL, _T("Test 2; Doesn't get here!"), _T("Test 2"), MB_OK);
return 0;
}
void rot13(char *ret, const char *in){
for( int i=0; i = sizeof(in); i++ ){
if(in[i] >= 'a' && in[i] <= 'm'){
// Crashes Here;
ret[i] += 13;
}
else if(in[i] > 'n' && in[i] <= 'z'){
// Possibly crashing Here too?
ret[i] -= 13;
}
else if(in[i] > 'A' && in[i] <= 'M'){
// Possibly crashing Here too?
ret[i] += 13;
}
else if(in[i] > 'N' && in[i] <= 'Z'){
// Possibly crashing Here too?
ret[i] -= 13;
}
}
}
The function gets to "Test 1; Does get Here!" - However it doesn't get to "Test 2; Doesn't get here!"
Thank you in advanced.
-Nick Daniels.
str is uninitialised and it is being dereferenced in rot13, causing the crash. Allocate memory for str before passing to rot13() (either on the stack or dynamically):
char str[1024] = ""; /* Large enough to hold string and initialised. */
The for loop inside rot13() is also incorrect (infinte loop):
for( int i=0; i = sizeof(in); i++ ){
change to:
for(size_t i = 0, len = strlen(in); i < len; i++ ){
You've got several problems:
You never allocate memory for your output - you never initialise the variable str. This is what's causing your crash.
Your loop condition always evaluates to true (= assigns and returns the assigned value, == tests for equality).
Your loop condition uses sizeof(in) with the intention of getting the size of the input string, but that will actually give you the size of the pointer. Use strlen instead.
Your algorithm increases or decreases the values in the return string by 13. The values you place in the output string are +/- 13 from the initial values in the output string, when they should be based on the input string.
Your algorithm doesn't handle 'A', 'n' or 'N'.
Your algorithm doesn't handle any non-alphabetic characters, yet the test string you use contains two.

Best algorithm to find all possible permutation of given binary bits

I am looking for an optimal algorithm to find out remaining all possible permutation
of a give binary number.
For ex:
Binary number is : ........1. algorithm should return the remaining 2^7 remaining binary numbers, like 00000001,00000011, etc.
Thanks,
sathish
The example given is not a permutation!
A permutation is a reordering of the input.
So if the input is 00000001, 00100000 and 00000010 are permutations, but 00000011 is not.
If this is only for small numbers (probably up to 16 bits), then just iterate over all of them and ignore the mismatches:
int fixed = 0x01; // this is the fixed part
int mask = 0x01; // these are the bits of the fixed part which matter
for (int i=0; i<256; i++) {
if (i & mask == fixed) {
print i;
}
}
to find all you aren't going to do better than looping over all numbers e.g. if you want to loop over all 8 bit numbers
for (int i =0; i < (1<<8) ; ++i)
{
//do stuff with i
}
if you need to output in binary then look at the string formatting options you have in what ever language you are using.
e.g.
printf("%b",i); //not standard in C/C++
for calculation the base should be irrelavent in most languages.
I read your question as: "given some binary number with some bits always set, create the remaining possible binary numbers".
For example, given 1xx1: you want: 1001, 1011, 1101, 1111.
An O(N) algorithm is as follows.
Suppose the bits are defined in mask m. You also have a hash h.
To generate the numbers < n-1, in pseudocode:
counter = 0
for x in 0..n-1:
x' = x | ~m
if h[x'] is not set:
h[x'] = counter
counter += 1
The idea in the code is to walk through all numbers from 0 to n-1, and set the pre-defined bits to 1. Then memoize the resulting number (iff not already memoized) by mapping the resulting number to the value of a running counter.
The keys of h will be the permutations. As a bonus the h[p] will contain a unique index number for the permutation p, although you did not need it in your original question, it can be useful.
Why are you making it complicated !
It is as simple as the following:
// permutation of i on a length K
// Example : decimal i=10 is permuted over length k= 7
// [10]0001010-> [5] 0000101-> [66] 1000010 and 33, 80, 40, 20 etc.
main(){
int i=10,j,k=7; j=i;
do printf("%d \n", i= ( (i&1)<< k + i >>1); while (i!=j);
}
There are many permutation generating algorithms you can use, such as this one:
#include <stdio.h>
void print(const int *v, const int size)
{
if (v != 0) {
for (int i = 0; i < size; i++) {
printf("%4d", v[i] );
}
printf("\n");
}
} // print
void visit(int *Value, int N, int k)
{
static level = -1;
level = level+1; Value[k] = level;
if (level == N)
print(Value, N);
else
for (int i = 0; i < N; i++)
if (Value[i] == 0)
visit(Value, N, i);
level = level-1; Value[k] = 0;
}
main()
{
const int N = 4;
int Value[N];
for (int i = 0; i < N; i++) {
Value[i] = 0;
}
visit(Value, N, 0);
}
source: http://www.bearcave.com/random_hacks/permute.html
Make sure you adapt the relevant constants to your needs (binary number, 7 bits, etc...)
If you are really looking for permutations then the following code should do.
To find all possible permutations of a given binary string(pattern) for example.
The permutations of 1000 are 1000, 0100, 0010, 0001:
void permutation(int no_ones, int no_zeroes, string accum){
if(no_ones == 0){
for(int i=0;i<no_zeroes;i++){
accum += "0";
}
cout << accum << endl;
return;
}
else if(no_zeroes == 0){
for(int j=0;j<no_ones;j++){
accum += "1";
}
cout << accum << endl;
return;
}
permutation (no_ones - 1, no_zeroes, accum + "1");
permutation (no_ones , no_zeroes - 1, accum + "0");
}
int main(){
string append = "";
//finding permutation of 11000
permutation(2, 6, append); //the permutations are
//11000
//10100
//10010
//10001
//01100
//01010
cin.get();
}
If you intend to generate all the string combinations for n bits , then the problem can be solved using backtracking.
Here you go :
//Generating all string of n bits assuming A[0..n-1] is array of size n
public class Backtracking {
int[] A;
void Binary(int n){
if(n<1){
for(int i : A)
System.out.print(i);
System.out.println();
}else{
A[n-1] = 0;
Binary(n-1);
A[n-1] = 1;
Binary(n-1);
}
}
public static void main(String[] args) {
// n is number of bits
int n = 8;
Backtracking backtracking = new Backtracking();
backtracking.A = new int[n];
backtracking.Binary(n);
}
}